标签:
原题链接 : 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.
使用两个栈,stack1和stack2。
http://www.ninechapter.com/problem/49/
1 public class Solution { 2 private Stack<Integer> stack1; 3 private Stack<Integer> stack2; 4 5 public Solution() { 6 // do initialization if necessary 7 stack1 = new Stack<Integer>(); 8 stack2 = new Stack<Integer>(); 9 } 10 11 public void push(int element) { 12 // write your code here 13 stack1.push(element); 14 } 15 16 public int pop() { 17 // write your code here 18 if (stack2.isEmpty()) { 19 while (!stack1.isEmpty()) { 20 stack2.push(stack1.pop()); 21 } 22 } 23 24 return stack2.pop(); 25 } 26 27 public int top() { 28 // write your code here 29 // write your code here 30 if (stack2.isEmpty()) { 31 while (!stack1.isEmpty()) { 32 stack2.push(stack1.pop()); 33 } 34 } 35 36 return stack2.peek(); 37 } 38 }
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/stack/StackQueue.java
Lintcode: Implement Queue by Stacks 解题报告
标签:
原文地址:http://www.cnblogs.com/yuzhangcmu/p/4175494.html