Data Structures & Algorithms
Using Stacks In Queues
QueuesTo create a queue using two stacks, we use two main stacks: one (stack1) for adding new items and the other (stack2) for removing items in the correct order. Here's how it works step by step:
Adding Items (Enqueue):
When we want to add an item to the queue, we always push it ontostack1. This is quick and easy because we don't have to worry about the order at this stage.Removing Items (Dequeue):
When we want to remove an item, the item at the front of the queue needs to be removed first (FIFO). However, since
stack1is a stack, the last item added is on top.To fix this, we move all the items from
stack1tostack2. This reverses their order so that the oldest item (the first one added) is now on top ofstack2.We then pop the top item from
stack2, which represents the front of the queue.
How It Works Together:
If
stack2already has items, we don't need to transfer anything fromstack1—we can directly pop fromstack2.If
stack2is empty, we move all the items fromstack1tostack2, ensuring the queue's order is correct.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 42 more lessons in Data Structures & Algorithms.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.