Implement stack using queues

LeetCode problem 225. Implement stack using queues.

## Problem description

Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (`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 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"]
[[], [1], [2], [], [], []]

```

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 such that each operation is **amortized** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer. You can use more than two queues.
## Approach 1: using two queues

One basic approach is to use two queues: **queue 1** and **queue 2**.

At least one of the two queues must be empty at any moment.

So the space complexity is **O(n)**.

Push
* If both queues are empty, push to queue 1.
* Otherwise, push to the stack that is non-empty.

The time complexity for this is **O(1)**.
Pop
* If both queues are empty, then do nothing.
* Otherwise, pick the queue that is non-empty, and do the following:
	1. Pull off all elements but the first element from the non-empty queue, and push these elements to the other queue, preserving the order.
	2. Pop the last element from the original queue. This becomes the return value (i.e. the top element of the stack, from the user's perspective).

The time complexity for this is **O(n)**, where *n* is the number of total elements in the data.
Top
1. First, do the same thing as in the pop operation. Get the top value of the stack.
	* After this step, elements must have been transferred from the original non-empty queue to the other queue.
2. Insert back this top value into the non-empty queue.

The time complexity for this is **O(n)**, where *n* is the number of total elements in the data. This is the same as in the pop operation.
Empty
We just need to check if both queues are empty.
The time complexity for this is **O(1)**.
### Solution

#### C++

```
#include <queue>

class MyStack {
private:
 typedef std::queue<int> IntQueue;

 IntQueue queue1;
 IntQueue queue2;

public:
 static const int FAIL = -1;

 /\*\* Initialize your data structure here. \*/
 MyStack() {
 queue1 = IntQueue();
 queue2 = IntQueue();
 }

 /\*\* Push element x onto stack. \*/
 void push(const int& x) {
 if (this->empty()) {
 queue1.push(x);
 }
 else {
 IntQueue& queueToPush = queue1.empty() ? queue2 : queue1;
 queueToPush.push(x);
 }
 }

 /\*\* Removes the element on top of the stack and returns that element. \*/
 int pop() {
 if (this->empty()) {
 return FAIL;
 }
 else {
 // pop the top value from the non-empty queue
 // transfer all remaining values to the other queue
 // NOTE: In C++ the return type for queue pop is void
 IntQueue& queueToPop = queue1.empty() ? queue2 : queue1;
 IntQueue& otherQueue = (queueToPop == queue1) ? queue2 : queue1;
 while (queueToPop.size() > 1) {
 int front = queueToPop.front();
 queueToPop.pop();
 otherQueue.emplace(front);
 }
 int result = queueToPop.front();
 queueToPop.pop();
 return result;
 }
 }

 /\*\* Get the top element. \*/
 int top() {
 if (this->empty()) {
 return FAIL;
 }
 else {
 int result = this->pop();
 this->push(result);
 return result;
 }
 }

 /\*\* Returns whether the stack is empty. \*/
 bool empty() {
 return queue1.empty() && queue2.empty();
 }
};

/\*\*
 \* 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();
 \* bool param\_4 = obj->empty();
 \*/

```

#### Java

```
class MyStack {

 private LinkedList<Integer> queue1;
 private LinkedList<Integer> queue2;

 public static final int FAIL = -1;

 /\*\* Initialize your data structure here. \*/
 public MyStack() {
 queue1 = new LinkedList<>();
 queue2 = new LinkedList<>();
 }

 /\*\* Push element x onto stack. \*/
 public void push(int x) {
 // if both of the queues are empty, then use queue 1
 if (this.empty()) {
 queue1.offerLast(x);
 }
 // otherwise use the non-empty one
 else {
 LinkedList<Integer> queueToPush = queue1.isEmpty() ? queue2 : queue1;
 queueToPush.offerLast(x);
 }
 }

 /\*\* Removes the element on top of the stack and returns that element. \*/
 public int pop() {
 if (this.empty()) {
 return FAIL;
 }
 else {
 // pop from the non-empty queue
 LinkedList<Integer> queueToPop = queue1.isEmpty() ? queue2 : queue1;
 LinkedList<Integer> otherQueue = (queueToPop == queue1) ? queue2 : queue1;
 while (queueToPop.size() > 1) {
 otherQueue.offerLast(queueToPop.pollFirst());
 }
 Integer result = queueToPop.pollFirst();
 return result;
 }
 }

 /\*\* Get the top element. \*/
 public int top() {
 if (this.empty()) {
 return FAIL;
 }
 else {
 // pop from the non-empty queue to get the result
 Integer result = this.pop();

 // insert back to the non-empty queue
 this.push(result);

 return result;
 }
 }

 /\*\* Returns whether the stack is empty. \*/
 public boolean empty() {
 return queue1.isEmpty() && queue2.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();
 \*/

```

## Notes

### C++

* `std::queue`
	+ In C++ queues, elements are pushed at the back and popped from the front.
	+ In C++ the `pop` method has return type `void`. Hence it *cannot* be used to retrieve the top value.

### Java

* `Deque` implementation classes:
	+ `ArrayDeque`
	+ `LinkedList`
* Allowed methods in this problem:
	+ Insert at the end: `addLast(e)` / `offerLast(e)`
	+ Pop from the front: `removeFirst(e)` / `pollFirst(e)`

Summary of `Deque` methods in Java (source)
 Insert