|
| 1 | +import java.util.LinkedList; |
| 2 | +import java.util.Queue; |
| 3 | + |
| 4 | +/* |
| 5 | + * @lc app=leetcode.cn id=225 lang=java |
| 6 | + * |
| 7 | + * [225] 用队列实现栈 |
| 8 | + */ |
| 9 | + |
| 10 | +// @lc code=start |
| 11 | +class MyStack { |
| 12 | + Queue<Integer> queue1; |
| 13 | + Queue<Integer> queue2; |
| 14 | + |
| 15 | + /** Initialize your data structure here. */ |
| 16 | + public MyStack() { |
| 17 | + queue1 = new LinkedList<>(); |
| 18 | + queue2 = new LinkedList<>(); |
| 19 | + } |
| 20 | + |
| 21 | + /** Push element x onto stack. */ |
| 22 | + public void push(int x) { |
| 23 | + queue1.add(x); |
| 24 | + } |
| 25 | + |
| 26 | + /** Removes the element on top of the stack and returns that element. */ |
| 27 | + public int pop() { |
| 28 | + while(queue1.size()>1){ |
| 29 | + queue2.add(queue1.poll()); |
| 30 | + } |
| 31 | + int temp = queue1.poll(); |
| 32 | + |
| 33 | + while(!queue2.isEmpty()){ |
| 34 | + queue1.add(queue2.poll()); |
| 35 | + } |
| 36 | + |
| 37 | + return temp; |
| 38 | + } |
| 39 | + |
| 40 | + /** Get the top element. */ |
| 41 | + public int top() { |
| 42 | + while(queue1.size()>1){ |
| 43 | + queue2.add(queue1.poll()); |
| 44 | + } |
| 45 | + int temp = queue1.peek(); |
| 46 | + |
| 47 | + queue2.add(queue1.poll()); |
| 48 | + |
| 49 | + while(!queue2.isEmpty()){ |
| 50 | + queue1.add(queue2.poll()); |
| 51 | + } |
| 52 | + return temp; |
| 53 | + } |
| 54 | + |
| 55 | + /** Returns whether the stack is empty. */ |
| 56 | + public boolean empty() { |
| 57 | + return queue1.isEmpty(); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Your MyStack object will be instantiated and called as such: |
| 63 | + * MyStack obj = new MyStack(); |
| 64 | + * obj.push(x); |
| 65 | + * int param_2 = obj.pop(); |
| 66 | + * int param_3 = obj.top(); |
| 67 | + * boolean param_4 = obj.empty(); |
| 68 | + */ |
| 69 | +// @lc code=end |
| 70 | + |
0 commit comments