Implement Stack using Queues
2015-07-08 13:10
405 查看
class MyStack { // Two queues. Queue<Integer> queue1 = new LinkedList<Integer>(); Queue<Integer> queue2 = new LinkedList<Integer>(); // Push element x onto stack. public void push(int x) { if (empty()) { queue1.offer(x); } else { if (queue1.size() > 0) { queue2.offer(x); int size = queue1.size(); while (size > 0) { queue2.offer(queue1.poll()); size--; } } else { queue1.offer(x); int size = queue2.size(); while (size > 0) { queue1.offer(queue2.poll()); size--; } } } } // Removes the element on top of the stack. public void pop() { if (empty()) { return; } else if (queue1.size() > 0) { queue1.poll(); } else { queue2.poll(); } } // Get the top element. public int top() { if (empty()) { return Integer.MAX_VALUE; } else if (queue1.size() > 0) { return queue1.peek(); } else { return queue2.peek(); } } // Return whether the stack is empty. public boolean empty() { return queue1.isEmpty() && queue2.isEmpty(); } }
相关文章推荐
- Mysql Error Code : 1436 Thread stack overrun
- 基于java中stack与heap的区别,java中的垃圾回收机制的相关介绍
- Python算法之栈(stack)的实现
- Stack数据结构的特点后进先出的应用:大数据运算
- C 堆栈,运行时类型挷定
- jstack和线程dump分析
- c语言stack实现--数据域与指针域分开
- 深入Java虚拟机
- 搭建CloudStack
- 新手,正在学Java Collection,瞎写点东西-一个基于链表的stack及其遍历
- 转贴一份挺好的堆和栈区别的资料
- parse in programming
- 百田笔试题
- Binary Tree Preorder Traversal
- [LeetCode] Valid Parenthese
- [Leetcode] Generate Parentheses
- [Leetcode] Postorder Traverse of Binary Tree
- [LeetCode] Valid Parentheses
- Binary Tree Zigzag Level Order Traversal
- Min Stack