Circular Queue using Linked List
🌀 What is a Circular Queue?
-
A circular queue is a special type of queue where the last node is connected back to the first node to make a circle.
-
It helps efficiently utilize the memory — when we reach the end, we wrap around to the beginning if there is free space.
-
It follows FIFO (First In First Out) like a normal queue.
✅ Using a linked list, we can model this naturally because linked lists are dynamic — we can add/delete nodes without worrying about fixed size.
✍️ Basic Operations
-
Enqueue (Insert):
-
Add a new element at the rear.
-
-
Dequeue (Delete):
-
Remove an element from the front.
-
-
Display:
-
Show all elements from front to rear (wrapping around if needed).
-
Algorithm to implement Circular Queue using Linked List
1. Node Structure:
-
Each node contains
data
andnext
pointer.
2. Enqueue (Insert at Rear):
-
Create a new node.
-
If queue is empty, make both
front
andrear
point to the new node. Setrear->next = front
. -
Else, insert the new node after
rear
, updaterear
, and linkrear->next
tofront
.
3. Dequeue (Delete from Front):
-
If queue is empty, show underflow.
-
If only one node (front == rear), delete it and make front and rear NULL.
-
Else, move front to
front->next
, updaterear->next = front
, and free old front node.
4. Display:
-
Start from
front
and move till you reach back tofront
again.
Comments
Post a Comment