Implement Stack using Queues
2016-06-10 01:55
267 查看
这道题可以用一个queue来实现,但在push方法中创建一个临时的queue,来实现倒置已有元素,这个思路很好。
参考:点击打开链接
class MyStack {
Queue<Integer> queue = new LinkedList<>();
// Push element x onto stack.
public void push(int x) {
Queue<Integer> temp = new LinkedList<>();
while (queue.size() > 0) {
temp.offer(queue.peek());
queue.poll();
}
queue.offer(x);
while (temp.size() > 0) {
queue.offer(temp.peek());
temp.poll();
}
}
// Removes the element on top of the stack.
public void pop() {
queue.poll();
}
// Get the top element.
public int top() {
return queue.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}
参考:点击打开链接
class MyStack {
Queue<Integer> queue = new LinkedList<>();
// Push element x onto stack.
public void push(int x) {
Queue<Integer> temp = new LinkedList<>();
while (queue.size() > 0) {
temp.offer(queue.peek());
queue.poll();
}
queue.offer(x);
while (temp.size() > 0) {
queue.offer(temp.peek());
temp.poll();
}
}
// Removes the element on top of the stack.
public void pop() {
queue.poll();
}
// Get the top element.
public int top() {
return queue.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}
相关文章推荐
- iOS 【UIKit-代码/xib 自定义控件】
- String.valueOf() 方法的使用
- [LeetCode]problem 62. Unique Paths
- [LeetCode]problem 63. Unique Paths II
- 让FineUI数据绑定支持dynamic对象
- iOS 【UIKit-属性中引用UI控件要用weak的原因】
- iOS 【UIKit-关于layoutSubviews的几点看法】
- iOS 【UIKit-UIScrollView 无法滚动的原因/两种情况下的弹簧效果】
- iOS 【UIKit-UITextField 退出键盘的几种方式/监听方式】
- UIKit:switch和slider控件的简单用法
- UIKit:segemented control控件以及ActiveIndicator的简单使用
- UIKit:progressView控件的使用
- iOS 【UIKit-UIPageControl 两个属性】
- 虚幻引擎4系列教程3(霜之小刀)(附视频)--游戏是需要逻辑的
- 项目总结1 UITabBarController为根视图的界面搭建
- The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support.
- 发现小米MUI系统有bug
- BIOS/UEFI基础——第一条指令
- android ui 练习
- [线性常微分方程][5]SPECIAL CASES REPEATED AND ZERO EIGENVALUES