原題:#232_用棧實現隊列
- 棧:先進後出
- 隊列:先進先出
- 使用兩個棧A,B。進棧時進入A,出棧時先從A出,進入B,再從B出。這時就可以實現先進先出了
class MyQueue {
private Stack<Integer> in = new Stack<>();
private Stack<Integer> out = new Stack<>();
public void push(int x) {
in.push(x);
}
public int pop() {
in2out();
return out.pop();
}
public int peek() {
in2out();
return out.peek();
}
private void in2out() {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}