Stack & Queue
Restricted access lists implementing LIFO and FIFO retrieval behaviors.
What is Stack & Queue?
Stacks and Queues are fundamental linear data structures that restrict how elements are added and removed. A Stack follows the Last-In-First-Out (LIFO) principle, where elements are inserted (push) and removed (pop) from the same end (top). A Queue follows the First-In-First-Out (FIFO) principle, where elements are inserted (enqueue) at the rear and removed (dequeue) from the front.
Key Characteristics:
- Stack: Last-In-First-Out (LIFO) model
- Queue: First-In-First-Out (FIFO) model
- Push/Enqueue adds elements to the structure
- Pop/Dequeue removes elements in order
Complexity Analysis
How it Works Step-by-Step
- Stack Push: Increment top pointer and place element at stack[top].
- Stack Pop: Retrieve element at stack[top], then decrement top pointer.
- Queue Enqueue: Add element to rear index, updating rear pointer.
- Queue Dequeue: Retrieve element from front index, updating front pointer.
Code Implementation
Worked Trace Example
Pushing 10, then 20 onto a Stack: Stack contains [10, 20] (top).
Popping from Stack: removes 20. Stack contains [10].
Enqueueing 10, then 20 into a Queue: Queue contains [10 (front), 20 (rear)].
Dequeueing from Queue: removes 10. Queue contains [20].