题目

方法一:用输入栈和输出栈模拟队列
- 只有输出栈为空的时候才能将输入栈的元素补充到输出栈,
- 否则输出栈不为空,如果再从输入栈往输出栈填充元素,就会弄乱队列的先进先出规则,
- 而且当输出栈为空需要从输入栈补充元素时,必须一次性将输入栈的元素都弹出并且加到输出栈

class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
dumpstackIn();
return outStack.pop();
}
public int peek() {
dumpstackIn();
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
private void dumpstackIn(){
if (!outStack.isEmpty()) return;
while (!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43