- 2068 Bhadra · 6+2 marks
Dynamic implementation of queue
Short answer
Use a linked list with front and rear pointers. Enqueue adds a node at the rear; dequeue removes a node from the front. When the queue becomes empty, both pointers become NULL. No fixed capacity; operations take O(1) time.
Write an algorithm for the dynamic implementation of queue. Also verify your algorithm with necessary illustrations.
In dynamic implementation, queue nodes are allocated from the heap with malloc when an element is inserted and released with free when removed. A singly linked list with pointers front (deletion end) and rear (insertion end) is used, so the queue has no fixed capacity.
struct node { int info; struct node *next; };
struct node *front = NULL, *rear = NULL;
ENQUEUE(x)
- Allocate node
p; if NULL print "overflow" and stop. p->info = x; p->next = NULL.- If
rear == NULL(empty):front = rear = p. - Else:
rear->next = p; rear = p.
DEQUEUE()
- If
front == NULLprint "underflow" and stop. p = front; x = p->info.front = front->next.- If
front == NULLthenrear = NULL. free(p); returnx.
void enqueue(int x) {
struct node *p = (struct node *)malloc(sizeof(struct node));
if (!p) { printf("Overflow\n"); return; }
p->info = x; p->next = NULL;
if (rear == NULL) front = rear = p;
else { rear->next = p; rear = p; }
}
int dequeue(void) {
if (!front) { printf("Underflow\n"); return -1; }
struct node *p = front; int x = p->info;
front = front->next;
if (!front) rear = NULL;
free(p);
return x;
}
Verification (illustration)
| Operation | Queue (front -> rear) | front | rear |
|---|---|---|---|
| start | empty | NULL | NULL |
| enqueue(10) | 10 | 10 | 10 |
| enqueue(20) | 10, 20 | 10 | 20 |
| enqueue(30) | 10, 20, 30 | 10 | 30 |
| dequeue() returns 10 | 20, 30 | 20 | 30 |
| dequeue() returns 20 | 30 | 30 | 30 |
| dequeue() returns 30 | empty | NULL | NULL |
| dequeue() | underflow message | NULL | NULL |
after enqueue 10,20,30:
front rear
| |
v v
[10|*]->[20|*]->[30|NULL]
Elements leave in the order they entered (FIFO). Both operations are O(1).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Static vs dynamic implementation of list · Data Structure and Algorithm, chapter 3 · asked 2×
- Static vs dynamic implementation of stack · Data Structure and Algorithm, chapter 2
- Circular queue algorithm with conditions · Data Structure and Algorithm, chapter 2
- Linear queue using array · Data Structure and Algorithm, chapter 2 · asked 2×
- Stack and queue using linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- Why choose static or dynamic list · Data Structure and Algorithm, chapter 3
- Dynamic physical model with example · Simulation and Modeling, chapter 2 · asked 3×
- Dynamic model of armature-controlled DC motor · Control Systems, chapter 2
- Planning in dynamic environment; linked bar chart · Project Engineering, chapter 3
- Cristian's algorithm · Distributed System, chapter 5 · asked 3×