Web Toolbar by Wibiya

Pages

Saturday, April 23, 2011

Implement a queue using two stacks.

Solution #1: Suppose we have two stacks, s1 and s2. For enqueue operation we will simply push the data on s1. For dequeue, we will pop everything from s1 into s2 and will then pop from s2 and will again push everything back on s1.

Enqueue Operation:
- Push on s1

Dequeue Operation:
- Pop everything on s1 and push on s2
- Pop s2
- Pop everything on s2 and push again on s1

Now, the dequeue operation can be pretty time consuming when the stack is big. Also, two back to back dequeue operations will require needless moment of elements between two stacks. This can be optimized by letting elements stay in the s2 and en-queuing data to s1 and dequeuing from s2 till s2 becomes empty. So, essentially, we are reducing the number of stack transfers.

Enqueue Operation:
- Push on s1

Dequeue Operation:
- If s2 is not empty, pop from it
- If s2 is empty, pop everything on s1 and push in s2
- Pop s2

No comments: