LeetCode232-用栈实现队列
LeetCode232-用栈实现队列
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
| class MyQueue { private Stack<Integer> stack1; private Stack<Integer> stack2;
public MyQueue() { stack1 = new Stack<Integer>(); stack2 = new Stack<Integer>(); }
public void push(int x) { stack1.push(x); }
public int pop() { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } }
return stack2.pop(); }
public int peek() { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } return stack2.peek(); }
public boolean empty() { return stack1.isEmpty() && stack2.isEmpty(); } }
|