https://leetcode.com/problems/implement-queue-using-stacks/
- Stack
- Queue
- Design
Use one stack for input and one for output. Transfer only when needed.
Amortized O(1) per operation
O(n)
import java.util.*;
class MyQueue {
private Stack<Integer> in = new Stack<>();
private Stack<Integer> out = new Stack<>();
public void push(int x) {
in.push(x);
}
private void shift() {
if (out.isEmpty()) {
while (!in.isEmpty()) out.push(in.pop());
}
}
public int pop() {
shift();
return out.pop();
}
public int peek() {
shift();
return out.peek();
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}