Operations on Queue
Key operations performed on a queue data structure
Operations
Enqueue
Add an element to the rear of the queue.
-
Before adding an element to the queue, we check if the queue is full.
-
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. -
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. -
We can keep adding elements until the queue reaches its capacity.
Dequeue
Remove an element from the front of the queue.
-
Before removing an element, we check if the queue is empty.
-
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. -
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). -
If the queue becomes empty after this operation, we reset both
front
andrear
pointers.
IsFull
Check if the queue is full.
-
For a linear queue, the queue is full when
rear == capacity - 1
. -
For a circular queue, the queue is full when the next position of
rear
is thefront
((rear + 1) % capacity == front
).
IsEmpty
Check if the queue is empty.
-
The queue is empty when
front > rear
for a linear queue or whenfront == -1
andrear == -1
after initialization or reset. -
For circular queues, the queue is empty when
front == -1
.
Front
Retrieve the element at the front of the queue without removing it.
-
Before accessing the front, we check if the queue is empty.
-
If the queue is empty, this operation is invalid and usually throws an error or returns a null/undefined value.
-
If the queue isn't empty, we simply return the value at the
front
index.