Queue Algorithm

The Queue Using Array Algorithm is an implementation of the queue data structure using an array as its underlying storage. A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle, where elements are inserted at the rear end and removed from the front end. In this algorithm, two pointers, front and rear, are used to keep track of the first and last elements in the queue, respectively. When an element is enqueued, it is added at the rear end of the array, and the rear pointer is incremented. When an element is dequeued, it is removed from the front end, and the front pointer is incremented. The algorithm also includes a check for overflow and underflow conditions to ensure that the queue operates within the bounds of the array. One of the main advantages of implementing a queue using an array is its simplicity and ease of understanding. The algorithm provides clear rules for enqueueing and dequeueing elements and is easy to implement in most programming languages. However, there are some drawbacks to this approach. The primary disadvantage is the issue of array resizing, as a fixed-sized array may lead to overflow if the queue grows beyond its capacity. To overcome this limitation, a circular queue can be employed, where the front and rear pointers wrap around the array, effectively reusing the freed spaces from dequeued elements. Another issue is inefficient memory utilization, as dequeued elements leave empty spaces in the array that are not utilized. Despite these drawbacks, the Queue Using Array Algorithm serves as a useful and straightforward introduction to the concept of queues and their implementation.
package QueueLinkedList

type Node struct {
	data int
	next *Node
}

type Queue struct {
	rear *Node
}

func (list *Queue) Enqueue(i int) {
	data := &Node{data: i}
	if list.rear != nil {
		data.next = list.rear
	}
	list.rear = data
}

func (list *Queue) Dequeue() (int, bool) {
	if list.rear == nil {
		return 0, false
	}
	if list.rear.next == nil {
		i := list.rear.data
		list.rear = nil
		return i, true
	}
	current := list.rear
	for {
		if current.next.next == nil {
			i := current.next.data
			current.next = nil
			return i, true
		}
		current = current.next
	}
}

func (list *Queue) Peek() (int, bool) {
	if list.rear == nil {
		return 0, false
	}
	return list.rear.data, true
}

func (list *Queue) Get() []int {
	var items []int
	current := list.rear
	for current != nil {
		items = append(items, current.data)
		current = current.next
	}
	return items
}

func (list *Queue) IsEmpty() bool {
	return list.rear == nil
}

func (list *Queue) Empty() {
	list.rear = nil
}

LANGUAGE:

DARK MODE: