top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can we implement queue with the help of two stack ?

+5 votes
421 views
How can we implement queue with the help of two stack ?
posted Oct 29, 2013 by Vikas Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Keep 2 stacks, let's call them stack1 and stack2.

Queue
- Push the new element onto stack1

Dequeue
- If outbox is empty, refill it by popping each element from stack1 and pushing it onto stack2
- Pop and return the top element from stack2

Drawback
Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.

answer Oct 29, 2013 by Abhay Kulkarni
...