232. Implement Queue using Stacks
```java
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
popAllToStack1();
stack1.push(x);
}
public int pop() {
popAllToStack2();
return stack2.pop();
}
public int peek() {
popAllToStack2();
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
private void popAllToStack2() {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
private void popAllToStack1() {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
2 1
1 2
if we want push -> push second back
keep pushing
2
1
when peek, pop
pop all to stack2
1
2
if push again, pop all from stack 2 to 1
3
2
1
empty, check both stacks
T: O(xN)
*/
```
better idea
only when stack2 is Empty , we need to push stack1 to stack2, why?
because we already have queue pop and peak candidate, just pop or peek it from stack2
```java
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
popAllToStack2();
return stack2.pop();
}
public int peek() {
popAllToStack2();
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
private void popAllToStack2() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
```
Last updated