|
| 1 | +// 232. 用栈实现队列 |
| 2 | + |
| 3 | + |
| 4 | +/** |
| 5 | + * Your MyQueue object will be instantiated and called as such: |
| 6 | + * MyQueue obj = new MyQueue(); |
| 7 | + * obj.push(x); |
| 8 | + * int param_2 = obj.pop(); |
| 9 | + * int param_3 = obj.peek(); |
| 10 | + * boolean param_4 = obj.empty(); |
| 11 | + */ |
| 12 | + |
| 13 | + |
| 14 | +/* |
| 15 | +1、stack1作为队列,元素正序。stack2作为辅助工具,不存放元素 |
| 16 | +2、push:先把stack1倒入stack2,元素压入stack1,再把stack2倒入stack1。实现了新元素在栈底,且整体正序 |
| 17 | +3、pop:直接弹出stack1栈顶 |
| 18 | +4、peek:直接查看stack1栈顶 |
| 19 | +5、empty:直接判断stack1是否为空 |
| 20 | + */ |
| 21 | +class MyQueue { |
| 22 | + private Stack<Integer> stack1; |
| 23 | + private Stack<Integer> stack2; |
| 24 | + |
| 25 | + public MyQueue() { |
| 26 | + stack1 = new Stack<>(); |
| 27 | + stack2 = new Stack<>(); |
| 28 | + } |
| 29 | + |
| 30 | + public void push(int x) { |
| 31 | + while (!stack1.isEmpty()) { |
| 32 | + stack2.push(stack1.pop()); |
| 33 | + } |
| 34 | + stack1.push(x); |
| 35 | + while (!stack2.isEmpty()) { |
| 36 | + stack1.push(stack2.pop()); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public int pop() { |
| 41 | + return stack1.pop(); |
| 42 | + } |
| 43 | + |
| 44 | + public int peek() { |
| 45 | + return stack1.peek(); |
| 46 | + } |
| 47 | + |
| 48 | + public boolean empty() { |
| 49 | + return stack1.isEmpty(); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | + |
| 54 | +/* |
| 55 | +1、stack1作为栈,元素倒序。stack2作为队列,元素正序 |
| 56 | +2、push:入栈就入stack1。push时如果stack1为空,记录队首元素,再入栈。队首元素用于peek时直接返回 |
| 57 | +3、pop:出栈就出stack2。stack2如果为空就把stack1倒入stack2,stack2不为空就弹出栈顶 |
| 58 | +4、peek:查看队首元素。stack2不为空那么栈顶就是队首,stack2为空那么就返回stack1记录的栈底队首元素 |
| 59 | +5、empty:stack1和stack2都为空时则空 |
| 60 | + */ |
| 61 | +class MyQueue { |
| 62 | + private Stack<Integer> stack1; |
| 63 | + private Stack<Integer> stack2; |
| 64 | + private int head; |
| 65 | + |
| 66 | + public MyQueue() { |
| 67 | + stack1 = new Stack<>(); |
| 68 | + stack2 = new Stack<>(); |
| 69 | + } |
| 70 | + |
| 71 | + public void push(int x) { |
| 72 | + if (stack1.isEmpty()) { |
| 73 | + head = x; |
| 74 | + } |
| 75 | + stack1.push(x); |
| 76 | + } |
| 77 | + |
| 78 | + public int pop() { |
| 79 | + if (stack2.isEmpty()) { |
| 80 | + while (!stack1.isEmpty()) { |
| 81 | + stack2.push(stack1.pop()); |
| 82 | + } |
| 83 | + } |
| 84 | + return stack2.pop(); |
| 85 | + } |
| 86 | + |
| 87 | + public int peek() { |
| 88 | + if (!stack2.isEmpty()) { |
| 89 | + return stack2.peek(); |
| 90 | + } |
| 91 | + return head; |
| 92 | + } |
| 93 | + |
| 94 | + public boolean empty() { |
| 95 | + return stack1.isEmpty() && stack2.isEmpty(); |
| 96 | + } |
| 97 | +} |
| 98 | + |
0 commit comments