Implement Queue using Stacks

A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be stack1 and stack2. q can be implemented in two ways:

Method 1 (By making enQueue operation costly)
This method makes sure that newly entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used.

enQueue(q, x)
1) While stack1 is not empty, push everything from satck1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
dnQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it

Method 2 (By making deQueue operation costly)
In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned.

enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).
deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything from satck1 to stack2.
3) Pop the element from stack2 and return it.

Method 2 is definitely better than method 1. Method 1 moves all the elements twice in enQueue operation, while method 2 (in deQueue operation) moves the elements once and moves elements only if stack2 empty.

Queue can also be implemented using one user stack and one Function Call Stack.
Below is modified Method 2 where recursion (or Function Call Stack) is used to implement queue using only one user defined stack.

enQueue(x)
1) Push x to stack1.
deQueue:
1) If stack1 is empty then error.
2) If stack1 has only one element then return it.
3) Recursively pop everything from the stack1, store the popped item
in a variable res, push the res back to stack1 and return res

The step 3 makes sure that the last popped item is always returned and since the recursion stops when there is only one item in stack1 (step 2), we get the last element of stack1 in dequeue() and all other items are pushed back in step 3.

Writing code in comment? Please use ideone.com and share the link here.

gaurav_sharma_17

/*
Queue can also be implemented using one user stack and one Function Call Stack.
Below
is modified Method 2 where recursion (or Function Call Stack) is used
to implement queue using only one user defined stack.

enQueue(x)
1) Push x to stack1.

deQueue:
1) If stack1 is empty then error.
2) If stack1 has only one element then return it.
3) Recursively pop everything from the stack1, store the popped item

in a variable res, push the res back to stack1 and return res

The
step 3 makes sure that the last popped item is always returned and
since the recursion stops when there is only one item in stack1 (step
2), we get the last element of stack1 in dequeue() and all other items
are pushed back in step 3.

I tried to write traverse func, but it got messed up here with main().

rengasami21

In method 2 (using two stacks), don’t we need to push all the elements back from stack 2 to stack 1? Because when we pop out for deque stack 1 becomes empty.

Am I missing something? Can somebody help me?

Abhishek Choudhery

No, the next element that you would want on the next pop operation is now at the top of Stack 2. See the Algo for Pop again!
Even I had the same doubt previously

rengasami21

Hi,

As per method 2 of using 2 stacks, we are popping every element of stack 1 and pushing it to stack 2 when we dequeue. So after this step, the stack 1 is empty. Now we are enqueuing an element, it will get added to stack 1. Now if we would like to dequeue an element, that one element will be popped out and pushed to stack 2, now if I pop from stack 2, it will give me only the element that was enqueued just now.

Don’t we need to push all the elements from Stack 2 to Stack 1 after dequeue?

Am I missing something here? Can somebody help me?

regards,
Rengasami R

yyk

yah…you r missing…point that….
“While dequeuing, when there are no elements in stack 2 u r pushing all elements in stack 1 to stack 2 not everytime,,,,,,when there are elements in stack 2, u dequeue directly from stack 2….without pushing elements from stack 1″

@all:
If we make stack using link-list then there is need to check the overflow condition in PUSH function. I think there is no limit on size of stack.Let me know if i am wrong.

Thanks…

Palash

One point that we all should note is that method one is amortized O(n), while method 2 is amortized O(1).

Joe Schulte

I think you can optimize this by only moving data from one stack to the other when needed. If you are en-queuing first make sure all the data is on stack 1, then push the new item on the top of 1. If you are de-queuing first make sure that all the data is on stack 2 then pop the top item from stack 2. This method doesn’t make one operation faster than the other. It favors doing more than one push or pop at a time, worst case is no worst than the previously stated methods.

@Ashok: Please take a closer look at the algorithm. Your last POP step doesn’t seem to follow the algorithm. As per the algo, B will be returned in last step.

rahul

plz tell in method 2 if i enqueue 123 den dequeue it willl dequeue 123 but suppose i called dequeue 2 times so stack 1 will have 123 and stack2 will have 3 and nw i enqueue in stack1 4 and then dequeue first 3 will be poped….but den dequeue called stack empty it will push 1234 in stack but 123 are of no use nw???plz xplain

WhatTheFuckAreYouSaying

LYK DIS F YU CRY EVRYTYME

Water

Awesome…. i was asked by this question in interview and this point cleared me many points.. thanks !!

In the Dequeue function of Method2(Queue can also be implemented using one user stack and one Function Call Stack.) I sense there is a Bug.
Step 3(copy paste from above algo): 3) Recursively pop everything from the stack1, store the last dequeued item and return it

You don’t need to store the last de-queued element, as this condition will be met by step2. When you have popped all but the last element. Let me know if I missed something.

Thanks,
Sharat.

Sandeep

@Sharat: Your point is valid. I have modified the algorithm and added few more words about step3. The program was correct, so no modifications in program.

mrn

hi sandeep….
i dint get why are u using pointer to pointer while passing control from enqueue/dequeue to push/pop functions. Can’t it be implemented using single pointer reference. Moreover at each point u are dereferencing the pointer to update its value which would not be the case if u wud have used single pointer to both functions push() and pop(). Tell me if i am wrong..

mrn

@ sandeep
i dint get why are u using pointer to pointer while passing control from enqueue/dequeue to push/pop functions. Can’t it be implemented using single pointer reference. Moreover at each point u are dereferencing the pointer to update its value which would not be the case if u wud have used single pointer to both functions push() and pop(). Tell me if i am wrong..

mrn

sorry :)…
i was out of my mind. Got the point . If we pass single pointer variable then a copy of that pointer is created in called function.The changes are done at dereferenced locations but pointers in the calling function are not updated. For this reason we need pointer to pointer.