[LeetCode]Implement Queue using Stacks
2015-11-27 05:55
323 查看
俩stack模拟queue,每次往第一个里面push,要pop的时候pop第二个,如果第二个为空,先把第一个的都放到第二个里面,再pop第二个。平均下来每个数据的时间复杂度为o(1)
class MyQueue { // Push element x to the back of queue. Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int x) { stack1.push(x); } // Removes the element from in front of queue. public void pop() { if (!stack2.isEmpty()) { stack2.pop(); } else { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } stack2.pop(); } } // Get the front element. public int peek() { if (!stack2.isEmpty()) { return stack2.peek(); } else { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } return stack2.peek(); } } // Return whether the queue is empty. public boolean empty() { return stack1.isEmpty() && stack2.isEmpty(); } }
相关文章推荐
- UITableView的plain和group
- Escape Sequences
- UISegmentedControl更改圆角
- Class requires API level 3 (current min is 1):
- Unique Paths
- 关于UIScrollView自动调整inset问题
- requestAnimationFrame--进度条
- UIScrollView && UITableView相关属性汇总(2013)
- UIScrollView和UITableView总结
- UITableView tableHeaderView autolayout自动计算高度
- UITableView使用详解
- [leetcode]Implement Queue using Stacks
- UIAlertView弹出框
- Android Uiautomator工具使用
- UIActionSheet底部弹出框
- IOS之UILabel添加下划线
- GUI Frame(一)
- iPhone的UITextField-更改占位符文本颜色
- SPOJ LIS2 Another Longest Increasing Subsequence Problem 三维偏序最长链 CDQ分治
- mybatis:java.lang.IllegalArgumentException:Parameter Maps collection does notcontain value for ...