1.题目描述:
2.解法:(关键在于使用两个栈进行模拟)
class MyQueue {
Stack stackIn = new Stack<>();//入栈操作
Stack stackOut = new Stack<>();//出栈操作
public MyQueue() {
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
reverse();
return stackOut.pop();
}
public int peek() {
reverse();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
public void reverse() {
if (!stackOut.isEmpty()) return;
//一旦涉及pop、push就会调用;但是一旦出栈的栈中有元素,
//则不把入栈的元素放入(否则破环队列的先进先出),直到出栈的元素为空再入
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}



