Skip to main content

Enqueue and dequeue in circular queue

Short answer

A circular queue uses array modulo N to wrap around, reusing vacant front slots. Enqueue: if (rear+1)%N == front then overflow, else set front=0 on first element, adjust rear and insert. Dequeue: remove at front, if last element reset both pointers, else front = (front+1)%N. Example shows enqueues 10..50, dequeues, then enqueue 60,70 wrap around.

Define a queue. Explain enqueue and dequeue (insertion and deletion) operation in circular queue with example.

A queue is a linear data structure in which insertion takes place at one end, the rear, and deletion at the other end, the front. The element inserted first is removed first, so it follows FIFO (First In First Out).

In a circular queue the last position is joined to the first, so the array is treated as a ring and positions freed at the front are reused. Indices wrap around using the modulus operator.

Enqueue and dequeue

Algorithm ENQUEUE(CQ, N, x)      /* front = rear = -1 initially */
1. if (rear + 1) % N == front:
       print "Queue overflow"; return
2. if front == -1:               /* first element */
       front = rear = 0
   else
       rear = (rear + 1) % N
3. CQ[rear] = x

Algorithm DEQUEUE(CQ, N)
1. if front == -1:
       print "Queue underflow"; return
2. x = CQ[front]
3. if front == rear:             /* last element removed */
       front = rear = -1
   else
       front = (front + 1) % N
4. return x
  • Full condition: (rear + 1) % N == front
  • Empty condition: front == -1

Example (N = 5)

OperationArray contents (index 0 → N-1)frontrear
enqueue(10)10 _ _ _ _00
enqueue(20)10 20 _ _ _01
enqueue(30)10 20 30 _ _02
enqueue(40)10 20 30 40 _03
enqueue(50)10 20 30 40 5004
enqueue(60): (rear+1)%5 = 0 = front → Queue overflow10 20 30 40 5004
dequeue() returns 10_ 20 30 40 5014
dequeue() returns 20_ _ 30 40 5024
enqueue(60)60 _ 30 40 5020
enqueue(70)60 70 30 40 5021
enqueue(80): (rear+1)%5 = 2 = front → Queue overflow60 70 30 40 5021
dequeue() returns 3060 70 _ 40 5031

After two dequeues, enqueue(60) and enqueue(70) succeed by wrapping rear to index 0 and 1; a linear queue would have reported overflow.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 2 questions →