Implement Queue using Stacks
2015-07-09 14:37
453 查看
class MyQueue { // Using two stacks. Stack<Integer> s1 = new Stack<Integer>();// Pop out. Stack<Integer> s2 = new Stack<Integer>();// Cache. // Push element x to the back of queue. public void push(int x) { s2.push(x); } // Removes the element from in front of queue. public void pop() { if (empty()) { return; } if (s1.isEmpty()) { while (!s2.isEmpty()) { s1.push(s2.peek()); s2.pop(); } } s1.pop(); } // Get the front element. public int peek() { if (empty()) { return -1; } if (s1.isEmpty()) { while (!s2.isEmpty()) { s1.push(s2.peek()); s2.pop(); } } return s1.peek(); } // Return whether the queue is empty. public boolean empty() { return s1.isEmpty() && s2.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