Skip to main content

Circular queue with display operation

Short answer

Use an array with wrap‑around via modulo. Enqueue inserts if (rear+1)%N != front; dequeue removes if front != -1. Display traverses from front to rear using i=(i+1)%N without altering pointers, printing elements in FIFO order.

Write an algorithm to design a data structure that provides enqueue, dequeue and display operations. The first two are the normal circular queue operations and the last one returns all elements in the circular queue without removing them from queue.

A circular queue is an array treated as a ring: after index N − 1 the next position is 0. Variables: array CQ[0..N-1], front = rear = -1 (empty).

Algorithms

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

DEQUEUE()
1. if front == -1:  print "Queue underflow"; return
2. x = CQ[front]
3. if front == rear:  front = rear = -1
   else               front = (front + 1) % N
4. return x

DISPLAY()                      /* does not change front or rear */
1. if front == -1:  print "Queue empty"; return
2. i = front
3. loop:
       print CQ[i]
       if i == rear:  break
       i = (i + 1) % N

C implementation

#include <stdio.h>
#define N 5
int cq[N], front = -1, rear = -1;

void enqueue(int x) {
    if ((rear + 1) % N == front) {               /* full */
        printf("Queue overflow\n"); return;
    }
    if (front == -1) front = rear = 0;           /* first element */
    else rear = (rear + 1) % N;
    cq[rear] = x;
}

int dequeue(void) {
    if (front == -1) {                           /* empty */
        printf("Queue underflow\n"); return -1;
    }
    int x = cq[front];
    if (front == rear) front = rear = -1;        /* last element */
    else front = (front + 1) % N;
    return x;
}
void display(void) {
    if (front == -1) { printf("Queue empty\n"); return; }
    int i = front;
    while (1) {
        printf("%d ", cq[i]);
        if (i == rear) break;
        i = (i + 1) % N;
    }
    printf("\n");
}

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
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

display() at the end prints 30 40 50 60 70 (from front = 2 wrapping to rear = 1) and leaves the queue unchanged. Each operation takes O(1) time except display, which is O(n).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 2 questions →