Linked Representation Of Stack And Queue
Linked lists can be used to build stacks and queues.
Linked Stack
A stack follows:
Like a pile of plates.
Representation
Use the head of the linked list as the top of the stack.
Stack Operations
Push
Insert at the front.
Time: O(1)
Pop
Delete from the front.
Time: O(1)
Peek
Read the front node.
Time: O(1)
Linked Queue
A queue follows:
Like people standing in a line.
Representation
Keep two pointers:
frontrear
Queue Operations
Enqueue
Insert at the rear.
Time: O(1)
Dequeue
Delete from the front.
Time: O(1)
Complexity Summary
| Structure | Operation | Time |
|---|---|---|
| Stack | Push | O(1) |
| Stack | Pop | O(1) |
| Stack | Peek | O(1) |
| Queue | Enqueue | O(1) |
| Queue | Dequeue | O(1) |
| Queue | Front | O(1) |
Why Linked Lists Work Well Here
- insertion/deletion at ends can be done with pointer updates
- no fixed size is required
- overflow happens only when memory is full