232. Implement Queue using Stacks

哈哈开始自己写得太丑啦><没眼看

然后现在这个方法比较巧的地方是,在pop()的时候执行peek()

在peek()的时候把stack1里剩的都倒腾到stack2里面,这样如果stack2不为空就可以保持一致输出。

 1 class MyQueue {
 2     Stack<Integer> stack1 = new Stack<Integer>();
 3     Stack<Integer> stack2 = new Stack<Integer>();
 4     
 5     // Push element x to the back of queue.
 6     public void push(int x) {
 7         stack1.push(x);
 8     }
 9 
10     // Removes the element from in front of queue.
11     public void pop() {
12         peek();
13         if(!stack2.isEmpty()) {
14             stack2.pop();
15         }
16     }
17 
18     // Get the front element.
19     public int peek() {
20         if(stack2.isEmpty()) {
21             int size = stack1.size();
22             for(int i = 0; i < size; i++) {
23                 stack2.push(stack1.pop());
24             }
25         }
26         return stack2.peek();
27     }
28 
29     // Return whether the queue is empty.
30     public boolean empty() {
31         return stack1.isEmpty() && stack2.isEmpty();
32     }
33 }

 

posted @ 2016-07-28 23:58  warmland  阅读(105)  评论(0编辑  收藏  举报