Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement the MyStack class:
void push(int x) Pushes element x to the top of the stack.
int pop() Removes the element on the top of the stack and returns it.
int top() Returns the element on the top of the stack.
boolean empty() Returns true if the stack is empty, false otherwise.
Notes:
You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue’s standard operations.
This problem can be solved by using two queues and later also with 1 Queue as well.
Method 1 - 2 Queues with copy (By Making Push Operation costly)#
This method makes sure that newly entered element is always at the front of q1, so that pop operation just dequeues from q1. q2 is used to put every new element at front of q1.
So, q1 is our main queue for pop, top and empty, but q2 is like a temp queue.
push(x)
1) Enqueue x to q2
2) One by one dequeue everything from q1 and enqueue to q2.
3) Swap the names of q1 and q2
// Swapping of names is done to avoid one more movement of all elements// from q2 to q1.
Method 3 - 2 Queues (By Making Pop Operation costly)#
In push operation, the new element is always enqueued to q1. In pop() operation, if q2 is empty then all the elements except the last, are moved to q2. Finally the last element is dequeued from q1 and returned.
pop()
1) One by one dequeue everything except the last element from q1 and enqueue to q2.
2) Dequeue the last item of q1, the dequeued item is result, store it.
3) Swap the names of q1 and q2
4) Return the item stored in step 2
// Swapping of names is done to avoid one more movement of all elements from q2 to q1.