我的解法
class MyQueue {Stack<Integer> stackIn;Stack<Integer> stackOut;public MyQueue() {stackIn = new Stack<>();// 负责进栈stackOut = new Stack<>();// 负责出栈}public void push(int x) {// 把出栈元素全部放到进栈while (!stackOut.empty()) {stackIn.push(stackOut.pop());}stackIn.push(x);}public int pop() {// 把进栈元素全部放到出栈while (!stackIn.empty()) {stackOut.push(stackIn.pop());}return stackOut.pop();}public int peek() {// 应该返回出栈的栈顶while (!stackIn.empty()) {stackOut.push(stackIn.pop());}return stackOut.peek();}public boolean empty() {return stackIn.empty() && stackOut.empty();}
}/*** 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();*/
结合官方代码
class MyQueue {Stack<Integer> stackIn;Stack<Integer> stackOut;public MyQueue() {stackIn = new Stack<>();// 负责进栈stackOut = new Stack<>();// 负责出栈}public void push(int x) {stackIn.push(x);}public int pop() {dumpStackIn();return stackOut.pop();}public int peek() {// 应该返回出栈的栈顶dumpStackIn();return stackOut.peek();}public boolean empty() {return stackIn.empty() && stackOut.empty();}private void dumpStackIn() {// 把进栈元素全部放到出栈//如果出栈还有元素就不需要 if (!stackOut.empty())return;while (!stackIn.empty()) {stackOut.push(stackIn.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();*/
可改进的部分
在出栈的时候如果stackOut中有元素,则直接可以弹出;如果没有就把所有的stackIn元素倒入stackOut。
这样的话进栈的时候直接压入stackIn就可以。