AlgoDocs

Operations on Queue

Key operations performed on a queue data structure

Operations

In queue data structures, several key operations are performed to manage the elements. These operations include adding elements to the queue (enqueue), removing elements from the queue (dequeue), checking if the queue is full or empty, and accessing the front element of the queue. Below is a detailed explanation of each operation along with visualizations.

Enqueue

Enqueue is the operation to add an element to the rear of the queue. It is a fundamental operation in queue data structures, allowing elements to be added in a first-in-first-out (FIFO) manner.

Add an element to the rear of the queue.

  1. Before adding an element to the queue, we check if the queue is full.

  2. If the queue is full (rear == capacity - 1 for a linear queue or a circular condition in a circular queue), we get a Queue is Full and cannot add any more elements.

  3. If the queue isn't full, we increment the rear (rear = rear + 1 or adjust for circular queues) and insert the new element at the rear position.

  4. We can keep adding elements until the queue reaches its capacity.

Visualization of Enqueue Operation On Queue

Dequeue

Dequeue is the operation to remove an element from the front of the queue. It is essential for managing the order of elements in a queue, ensuring that elements are processed in the order they were added.

Remove an element from the front of the queue.

  1. Before removing an element, we check if the queue is empty.

  2. If the queue is empty (front > rear in a linear queue or a circular condition in a circular queue), we get a Queue is Empty and cannot remove any elements.

  3. If the queue isn't empty, we retrieve the element at the front and increment the front pointer (front = front + 1 or adjust for circular queues).

  4. If the queue becomes empty after this operation, we reset both front and rear pointers.

Visualization of Dequeue Operation On Queue

IsFull

Check if the queue is full.

  1. For a linear queue, the queue is full when rear == capacity - 1.

  2. For a circular queue, the queue is full when the next position of rear is the front ((rear + 1) % capacity == front).

Visualization of IsFull Operation On Queue

IsEmpty

Check if the queue is empty.

  1. The queue is empty when front > rear for a linear queue or when front == -1 and rear == -1 after initialization or reset.

  2. For circular queues, the queue is empty when front == -1.

Visualization of IsEmpty Operation On Queue

Front

Retrieve the element at the front of the queue without removing it.

  1. Before accessing the front, we check if the queue is empty.

  2. If the queue is empty, this operation is invalid and usually throws an error or returns a null/undefined value.

  3. If the queue isn't empty, we simply return the value at the front index.

Visualization of Front Operation On Queue

How is this guide?