首页 > 其他 > 详细

225. Implement Stack using Queues

时间:2016-10-13 11:35:56      阅读:196      评论:0      收藏:0      [点我收藏+]

不定期更新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 }

 

225. Implement Stack using Queues

原文:http://www.cnblogs.com/zslhq/p/5955773.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!