Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack
(
Implement the
-
void push(int x) Pushes elementx 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() Returnstrue if the stack is empty,false otherwise.
-
You must use only standard operations of a queue, which means that only
push to back ,peek/pop from front ,size andis 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.
Output: [null, null, null, 2, 2, false]
Explanation:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
Constraints:
1 <= x <= 9 - At most
100 calls will be made topush ,pop ,top , andempty . - All the calls to
pop andtop are valid.
Follow-up: Can you implement the stack using only one queue?
Contents
Solution 1 - Implementation of stack using one queue
In this approach, we are going to implement a
-
push(int x) : we will add the elementx to the queue. -
pop() : we will go through stack elements from1.....n-1 and remove these elements from top, and add it back to the stack. Say if the stack looks like this1, 2, 3,  .., .. , then after after poppingn-1 elements and add it back, it looks like this3, 2, 1,  .., .. , now we can simply pop the first element from the queue, it returns1 , note that pop() operation will also remove and return the element. -
top() : this operation is similar topop() , except at the end, we will make apeek() operation on queue, it returns the first element from the queue, but will not remove it. -
empty() : we will simply callqueue.isEmpty() , this returnstrue is the queue is empty,false otherwise.
Complexity Analysis:
Time complexity: In this implementation
Space complexity: O(n).
Above implementations source code can be found at