Lintcode: Implement Queue by Stacks 解题报告
2014-12-20 15:39
225 查看
Implement Queue by Stacks
原题链接 : http://lintcode.com/zh-cn/problem/implement-queue-by-stacks/#As the title described, you should only use two stacks to implement a queue's actions.
The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
样例
For push(1), pop(), push(2), push(3), top(), pop(), you should return 1, 2 and 2
挑战
implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.
public class Solution {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Solution() {
// do initialization if necessary
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void push(int element) {
// write your code here
stack1.push(element);
}
public int pop() {
// write your code here
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int top() {
// write your code here
// write your code here
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
}
View Code
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/stack/StackQueue.java
相关文章推荐
- Lintcode: Sort Colors II 解题报告
- Lintcode: Majority Number 解题报告
- Lintcode解题报告
- lintcode: k Sum 解题报告
- Lintcode: Subarray Sum 解题报告
- LintCode 解题记录 17.8.30 两个指针
- codeforces round 205 解题报告
- Codeforces Round #191 (Div. 2) 解题报告
- Codeforces Round #234 (Div. 2) 解题报告
- Codeforces Round #379 (Div. 2) 解题报告
- codevs 2622 数字序列 DP 解题报告
- codevs 1620 轮船问题 DP 解题报告
- CUGBACM Codeforces Tranning 2 解题报告
- [CODEVS1159]最大全0子矩阵解题报告
- 【codevs1045】 奶牛的旅行 解题报告
- Educational Codeforces Round 6 解题报告
- Codeforces AIM Tech Round (Div. 2)解题报告
- 【解题报告】Educational Codeforces Round 13
- codevs1298 凸包周长 解题报告
- Codeforces Round #342 (Div. 2) 解题报告