Stacks and Queues: Implementing Undo/Redo & Message Buffers
On this page
Stacks & Queues
Stacks and Queues are "Restricted" data structures. They don't allow you to access elements in the middle. They are designed for specific data flow patterns.
1. Stack (LIFO - Last In First Out)
Think of a stack of plates. You can only add/remove from the top.
- Push: Add an item.
- Pop: Remove the top item.
- Peek: Look at the top item without removing it.
2. Queue (FIFO - First In First Out)
Think of a line at a grocery store. The first person to join is the first person served.
- Enqueue: Add to the back.
- Dequeue: Remove from the front.
4. Interview Mastery
Q: "How can you implement a Queue using only two Stacks?"
Architect Answer: "You use one stack for 入队 (Enqueue) and one for 出队 (Dequeue). When you want to dequeue, and the 'Dequeue Stack' is empty, you pop everything from the 'Enqueue Stack' and push it into the 'Dequeue Stack'. This reverses the order, effectively turning LIFO into FIFO. This is a common logic test that evaluates your understanding of data flow manipulation."
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!