- 2073 Magh · 8 marks
Circular queue using linked list
Short answer
Maintain a rear pointer to the list’s last node; enqueue inserts a node after rear and updates rear; dequeue removes the front node (rear->next) and adjusts rear if the queue becomes empty. Both operations are O(1).
Write complete algorithm to implement circular queue linked list.
A circular queue using a linked list is a singly linked list whose last node points back to the first node. One pointer rear pointing to the last node is enough: rear->next is the front node. Insertion is done after rear, deletion from rear->next.
rear
|
v
[10|*]->[20|*]->[30|*]--+
^ (front) |
+-----------------------+
struct node { int info; struct node *next; };
struct node *rear = NULL; /* NULL means queue is empty */
ENQUEUE(x)
- Create node
p; if malloc fails print "overflow" and stop.p->info = x. - If
rear == NULL(empty):p->next = p(points to itself). - Else:
p->next = rear->next(new node points to the front);rear->next = p. rear = p.
DEQUEUE()
- If
rear == NULL, print "underflow" and stop. f = rear->next(front node);x = f->info.- If
f == rear(only one node):rear = NULL. - Else:
rear->next = f->next. free(f); returnx.
DISPLAY()
If rear == NULL print "empty". Else p = rear->next; do { print p->info; p = p->next; } while (p != rear->next);
void enqueue(int x) {
struct node *p = (struct node *)malloc(sizeof(struct node));
if (!p) { printf("Overflow\n"); return; }
p->info = x;
if (rear == NULL) p->next = p;
else { p->next = rear->next; rear->next = p; }
rear = p;
}
int dequeue(void) {
if (!rear) { printf("Underflow\n"); return -1; }
struct node *f = rear->next; int x = f->info;
if (f == rear) rear = NULL;
else rear->next = f->next;
free(f);
return x;
}
Trace
| Operation | Queue (front to rear) | rear |
|---|---|---|
| enqueue 1, 2, 3 | 1 2 3 | 3 |
| dequeue -> 1 | 2 3 | 3 |
| enqueue 4 | 2 3 4 | 4 |
| dequeue x3 -> 2, 3, 4 | empty | NULL |
(The C code was compiled and run on this sequence: it gives 1, then 2, 3, 4.) Both operations are O(1) and no space is wasted, unlike an array queue.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Circular queue algorithm with conditions · Data Structure and Algorithm, chapter 2
- Implement BST using doubly linked list · Data Structure and Algorithm, chapter 6
- Stack and queue using linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- Enqueue and dequeue in circular queue · Data Structure and Algorithm, chapter 2 · asked 2×
- Circular queue vs linear queue · Data Structure and Algorithm, chapter 2
- Circular queue with display operation · Data Structure and Algorithm, chapter 2