leetcode-java-225. Implement Stack using Queues
2016-06-15 22:04
447 查看
class MyStack { // Push element x onto stack. List<Integer> queue1 = new LinkedList<Integer>(); List<Integer> queue2 = new LinkedList<Integer>(); public void push(int x) { if(!queue1.isEmpty()) { queue1.add(x); } else { queue2.add(x); } } // Removes the element on top of the stack. public void pop() { // 两个队列中至少有一个为空,将queue1设置非空 if(queue1.isEmpty()) { List<Integer> tmp = queue2; queue2 = queue1; queue1 = tmp; } while(queue1.size() > 1) { queue2.add(queue1.remove(0)); } queue1.clear(); } // Get the top element. public int top() { // 两个队列中至少有一个为空,将queue1设置非空 if(queue1.isEmpty()) { List<Integer> tmp = queue2; queue2 = queue1; queue1 = tmp; } while(queue1.size() > 1) { queue2.add(queue1.remove(0)); } queue2.add(queue1.get(0)); return queue1.remove(0); } // Return whether the stack is empty. public boolean empty() { return queue1.isEmpty() && queue2.isEmpty(); } }
相关文章推荐
- UIView动画效果
- 找出一个数组中重复次数最多的字符暨找出Map中的最大Value及其对应的Key
- POJ 2785-4 Values whose Sum is 0(a+b+c+d=0-折半枚举)
- Anroid UI
- C#实现的 快速查找通用组件 YHSoft.QuickFind
- Leetcode 347. Top K Frequent Elements
- Packet for query is too large
- N-Queens II
- 关于UIView位置信息的总结和CATransform3D初步认识
- 百度富文本编辑器UEditor的使用和他的图片上传
- Arduino串口高级用法
- Unique Paths II
- Unique Paths
- 232. Implement Queue using Stacks 还不理解法一
- 多线程更新UI的常用方法
- iOS学习之UINavigationController详解与使用(一)添加UIBarButtonItem
- Lightoj 1012 - Guilty Prince
- iOS UITextField的边框设置颜色的小坑
- IOS开发UIBarButtonItem-添加自定义Left或者Right按钮
- Codeforces 678F Lena and Queries