Implement Stack using Queues
2015-09-18 13:37
337 查看
始终保证有一个队列是空的!
class MyStack { // Push element x onto stack. Queue<Integer> q1 = new LinkedList<Integer>(); Queue<Integer> q2 = new LinkedList<Integer>(); public void push(int x) { if (q1.isEmpty()) { q2.add(x); } else{ q1.add(x); } } // Removes the element on top of the stack. public void pop() { if (q2.isEmpty()) { while (q1.size() != 1) { q2.add(q1.poll()); } q1.poll(); } else{ while (q2.size() != 1) { q1.add(q2.poll()); } q2.poll(); } } // Get the top element. public int top() { int tmp; if (q2.isEmpty()) { while (q1.size() != 1) { q2.add(q1.poll()); } tmp = q1.peek(); q2.add(q1.poll()); } else{ while (q2.size() != 1) { q1.add(q2.poll()); } tmp = q2.peek(); q1.add(q2.poll()); } return tmp; } // Return whether the stack is empty. public boolean empty() { return q1.isEmpty() && q2.isEmpty(); } }
相关文章推荐
- xcode7.0-iOS9新特性之三:界面适配利器:UIStackView
- UITabBarItem 如何触发点击事件
- 【Mockplus教程】重命名
- 【Mockplus教程】删除
- 【Mockplus教程】复制/克隆
- 关机时windows发的消息WM_QUERYENDSESSION
- 【Mockplus教程】收藏和重用
- 【Mockplus教程】标尺和参考线
- UILabel设置行间距及字体色彩
- Entity Framework 6 执行Linq to Entities异常"p__linq__1 : String truncation: max=0, len=2, value='测试'"
- UITextView
- UILabel textAlignment in IOS6
- easyUI之message
- (原创)iOS中cell高度自适应方法UITableView设置
- UILabel自适应高度和自动换行
- 让你明白response.sendRedirect()与request.getRequestDispatcher().forward()区别
- [!] Unable to satisfy the following requirements:众里寻他千百度。
- ecshop 的transport.js 与jqueyr冲突
- 交互设计的基本方法(概述篇)
- VirtualBox安装增强工具时:Unable to install guest additions: unknown filesystem type 'iso9660'