一遍过了,中间差一个判断
class MyQueue { Stack<Integer> a; Stack<Integer> b; public MyQueue() { a = new Stack<Integer>(); b = new Stack<Integer>(); } public void push(int x) { a.push(x); if(b.isEmpty()) b.push(x); } public int pop() { int ans = b.pop(); if(b.isEmpty()&&!a.isEmpty()){ while(!a.isEmpty()){ b.push(a.peek()); a.pop(); } if(b.peek()==ans) b.pop(); } return ans; } public int peek() { return b.peek(); } public boolean empty() { if(a.isEmpty()&&b.isEmpty()) return true; else return false; } } /** * 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(); */