⬅ Previous Topic
Stacks - LIFO Data StructureNext Topic ⮕
Linked Lists - Node-Based Data Structures⬅ Previous Topic
Stacks - LIFO Data StructureNext Topic ⮕
Linked Lists - Node-Based Data StructuresA Queue is a linear data structure that follows the FIFO (First In First Out) principle. The element that is inserted first is the one that gets removed first.
Imagine a line at a ticket counter — the person who comes first gets served first. This is exactly how a queue works in programming.
Queues are used in:
Initialize Queue as empty list
Function enqueue(item):
Add item to the end of Queue
Function dequeue():
If Queue is not empty:
Remove and return first element of Queue
Else:
Return "Queue Underflow"
Function front():
If Queue is not empty:
Return first element
Else:
Return "Queue is empty"
Function isEmpty():
Return true if Queue is empty, else false
Queue: [] Enqueue 10 → Queue: [10] Enqueue 20 → Queue: [10, 20] Dequeue → Returned: 10, Queue: [20] Front → 20 isEmpty → false
Why do we remove elements from the front instead of the rear in a queue?
Answer: Because a queue follows FIFO — the first element that comes in should be the first to go out, just like a queue in real life.
Suppose we want to limit the queue to a fixed capacity. We need to check for overflow before enqueuing new items.
Initialize Queue as empty list
Set MAX_SIZE = 3
Function enqueue(item):
If length of Queue == MAX_SIZE:
Return "Queue Overflow"
Else:
Add item to end of Queue
Function dequeue():
If Queue is empty:
Return "Queue Underflow"
Else:
Remove and return first element
Enqueue 1 → [1] Enqueue 2 → [1, 2] Enqueue 3 → [1, 2, 3] Enqueue 4 → Queue Overflow Dequeue → Returned 1, Queue: [2, 3]
How can we improve space usage when using a fixed-size queue?
Answer: Use a circular queue where the rear pointer wraps around to the front once it reaches the end, making better use of space.
In a circular queue, the last position is connected back to the first to form a circle. This allows insertion at the beginning when there's space available due to prior deletions at the front.
Implement a pseudocode queue that supports the following operations: enqueue, dequeue, front, size, isEmpty, and displayQueue().
Try adding elements beyond the queue size and removing elements from an empty queue to see how it behaves.
⬅ Previous Topic
Stacks - LIFO Data StructureNext Topic ⮕
Linked Lists - Node-Based Data StructuresYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.