GeeksforGeeks » Algorithms
Implement queue using stacks
(3 posts)
[closed]
-
How will implement queue using 2 stacks such that enqueue and dequeue operations are efficient
-
Here is a pseudo code using two stacks. Let two stacks be S1 and S2 and queue is Q.
For enqueue operation, push in buffer stack S1.
For dequeue operation, if S2 is not empty then pop and return top element of S2, otherwise push everything from S1 to S2 and then pop and return the top element of S2void enQueue(Q, x) { push (S1, x); } void deQueue(Q) { if (isStackEmpty(52)) { if (isStackEmpty(S1)) { print(”Q is empty”); return; } else { while (!(isStackEmpty(S1))) { x = pop(S1); push(S2, x) } } x = pop (S2); return x; } -
This has been published. Please see http://geeksforgeeks.org/?p=5009
Thanks all for your contribution.
Topic Closed
This topic has been closed to new replies.