225. Implement Stack using Queues
2016-02-17 00:42
393 查看
class MyStack {
Queue<Integer> q = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
q.add(x);
}
// Removes the element on top of the stack.
public void pop() {
int size = q.size();
for(int i = 1; i < size; i++)
q.add(q.remove());
q.remove();
}
// Get the top element.
public int top() {
int size = q.size();
for(int i = 1; i < size; i++)
q.add(q.remove());
int ret = q.remove();
q.add(ret);
return ret;
}
// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
}
Queue<Integer> q = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
q.add(x);
}
// Removes the element on top of the stack.
public void pop() {
int size = q.size();
for(int i = 1; i < size; i++)
q.add(q.remove());
q.remove();
}
// Get the top element.
public int top() {
int size = q.size();
for(int i = 1; i < size; i++)
q.add(q.remove());
int ret = q.remove();
q.add(ret);
return ret;
}
// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
}
相关文章推荐
- java基础学习总结——GUI编程(二)
- EasyUI学习总结(五)——EasyUI组件使用
- EasyUI学习总结(六)——EasyUI布局
- java基础学习总结——GUI编程(一)
- EasyUI学习总结(四)——parser源码分析
- 使用storyboard+继承UITableViewController创建TableView项目
- vue.js快速上手。
- HDOJ 1005 Number Sequence
- UICollectionView添加Header Footer没被调用
- 【每周一文】Supervised Sequence Labelling with Recurrent Neural Networks
- UI基础-05 HelloWorld 工程中的故事板文件
- (java) Unique Paths
- Building Maintainable Software-java篇之 Write Clean Code
- USACO 1.4 Search Techniques
- iOS开发UI篇—UIWindow简单介绍
- Building Maintainable Software-java篇之Automate Tests
- Hqueue Distributed Simulations(Houdini分机解算)
- UIPopoverController的使用
- Winform的ListBox的ValueMember和DisplayMember绑定的名称所属对象必须是Public的。
- DuiVision设计器预览版