# Question

Formatted question description: https://leetcode.ca/all/225.html

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.

Example 1:

Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], , , [], [], []]
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 to push, pop, top, and empty.
• All the calls to pop and top are valid.

Follow-up: Can you implement the stack using only one queue?

# Algorithm

Need two queues,

• 1st queue: A queue is used to put the last number added to simulate the top element of the stack.
• 2nd queue: All the remaining numbers are placed in the other queue in order.

When the push() operation, the new number is first added to the queue of the top element of the analog stack. If there is a number in the queue at this time, the original number is put into 2nd queue, and the new number is in 1st queue. To simulate the top element of the stack.

In the top()/peek() operation, if there is a number in the top of the 1st queue, it will return directly. If there is no number, it will go to 2nd queue and take out the last number by shifting the number and add it to the queue at the top of the 1st queue.

When pop() operation, perform top()/peek() operation first to ensure that there is a number in the queue at the top of the 1st queue, and then remove the number.

When the empty() operation, when both queues are empty, the stack is empty.

# Code

• import java.util.LinkedList;
import java.util.Queue;

public class Implement_Stack_using_Queues {
class MyStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;

public MyStack() {
}

// Push element x onto stack.
public void push(int x) {
queue1.offer(x);
}

// Removes the element on top of the stack.
public int pop() {
while (queue1.size() > 1) {
queue2.offer(queue1.poll());
}

int last = queue1.poll();

// Swap queue1 and queue2
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;

return last;
}

// Get the top element.
public int top() {
while (queue1.size() > 1) {
queue2.offer(queue1.poll());
}

// tried to re-use while part, but seems not achievable, since val is retrieved in-between
int ret = queue1.poll();
queue2.offer(ret); // note: add back to q2, so q1 will always be empty

// Swap queue 1 and queue2
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;

return ret;
}

// Return whether the stack is empty.
public boolean empty() {
return queue1.isEmpty();
}
}
}

############

class MyStack {

private Deque<Integer> q;

/** Initialize your data structure here. */
public MyStack() {
q = new ArrayDeque<>();
}

/** Push element x onto stack. */
public void push(int x) {
q.offerLast(x);
int n = q.size();
while (n-- > 1) {
q.offerLast(q.pollFirst());
}
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.pollFirst();
}

/** Get the top element. */
public int top() {
return q.peekFirst();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}

/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/

• // OJ: https://leetcode.com/problems/implement-stack-using-queues
// Time: O(N) for push, O(1) for others
// Space: O(1)
class MyStack {
queue<int> q;
public:
MyStack() {}
void push(int x) {
q.push(x);
for (int cnt = q.size() - 1; cnt > 0; --cnt) {
q.push(q.front());
q.pop();
}
}
int pop() {
int ans = q.front();
q.pop();
return ans;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};

• # one queue
class Stack:

def __init__(self):
self._queue = collections.deque()

def push(self, x):
q = self._queue
q.append(x)
for _ in range(len(q) - 1):
q.append(q.popleft())

def pop(self):
return self._queue.popleft()

def top(self):
return self._queue

def empty(self):
return not len(self._queue)

# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

############

from collections import deque

# two queues
class MyStack:

def __init__(self):
self.q1 = deque()
self.q2 = deque()

def push(self, x: int) -> None:
self.q1.append(x)

def pop(self) -> int:
while len(self.q1) != 1:
self.q2.append(self.q1.popleft())

val = self.q1.popleft()
self.q1, self.q2 = self.q2, self.q1
return val

def top(self) -> int:
while len(self.q1) != 1:
self.q2.append(self.q1.popleft())

# tried to re-use while part, but seems not achievable, since val is retrieved in-between
val = self.q1
self.q2.append(self.q1.popleft())  # note: add back to q2, so q1 will always be empty

self.q1, self.q2 = self.q2, self.q1
return val

def empty(self) -> bool:
return not self.q1

# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

• type MyStack struct {
q1 []int
q2 []int
}

func Constructor() MyStack {
return MyStack{}
}

func (this *MyStack) Push(x int) {
this.q2 = append(this.q2, x)
for len(this.q1) > 0 {
this.q2 = append(this.q2, this.q1)
this.q1 = this.q1[1:]
}
this.q1, this.q2 = this.q2, this.q1
}

func (this *MyStack) Pop() int {
x := this.q1
this.q1 = this.q1[1:]
return x
}

func (this *MyStack) Top() int {
return this.q1
}

func (this *MyStack) Empty() bool {
return len(this.q1) == 0
}

/**
* Your MyStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Empty();
*/

• class MyStack {
q1: number[] = [];
q2: number[] = [];

constructor() {}

push(x: number): void {
this.q2.push(x);
while (this.q1.length) {
this.q2.push(this.q1.shift()!);
}
[this.q1, this.q2] = [this.q2, this.q1];
}

pop(): number {
return this.q1.shift()!;
}

top(): number {
return this.q1;
}

empty(): boolean {
return this.q1.length === 0;
}
}

/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/