225. Implement Stack using Queues

不定期更新leetcode解题java答案。

采用pick one的方式选择题目。

题意为使用Queue队列的方式来代替Stack栈存储的某些方法,其中有pop(),push(),top(),empty()方法。

思路为将栈倒序存储利用Queue的本身函数来进行实现。代码如下:

 1 class MyStack {
 2     Queue<Integer> q = new LinkedList();
 3     // Push element x onto stack.
 4     public void push(int x) {
 5         for(int i = 0; i < q.size(); i++){
 6             q.offer(x);
 7             x = q.poll();
 8         }
 9         q.offer(x);
10     }
11 
12     // Removes the element on top of the stack.
13     public void pop() {
14         q.poll();
15     }
16 
17     // Get the top element.
18     public int top() {
19         return q.peek();
20     }
21 
22     // Return whether the stack is empty.
23     public boolean empty() {
24         return q.size() == 0;
25     }
26 }

 

posted @ 2016-10-13 11:19  zslhq~  阅读(112)  评论(0编辑  收藏  举报