Implement Queue by Two Stacks

Question

  1. As the title described, you should only use two stacks to implement a queue's actions.
  2. The queue should support push(element),
  3. pop() and top() where pop is pop the first(a.k.a front) element in the queue.
  4. Both pop and top methods should return the value of first element.
  5. Example
  6. For push(1), pop(), push(2), push(3), top(), pop(), you should return 1, 2 and 2
  7. Challenge
  8. implement it by two stacks, do not use any other data structure and push,
  9. pop and top should be O(1) by AVERAGE.

题解

两个栈模拟队列,栈是 LIFO, 队列是 FIFO, 故用两个栈模拟队列时可结合栈1和栈2, LIFO + LIFO ==> FIFO, 即先将一个栈元素全部 push 到另一个栈,效果即等价于 Queue.

Java

  1. public class Solution {
  2. private Stack<Integer> stack1;
  3. private Stack<Integer> stack2;
  4. public Solution() {
  5. // source stack
  6. stack1 = new Stack<Integer>();
  7. // target stack
  8. stack2 = new Stack<Integer>();
  9. }
  10. public void push(int element) {
  11. stack1.push(element);
  12. }
  13. public int pop() {
  14. if (stack2.empty()) {
  15. stack1ToStack2(stack1, stack2);
  16. }
  17. return stack2.pop();
  18. }
  19. public int top() {
  20. if (stack2.empty()) {
  21. stack1ToStack2(stack1, stack2);
  22. }
  23. return stack2.peek();
  24. }
  25. private void stack1ToStack2(Stack<Integer> stack1, Stack<Integer> stack2) {
  26. while (!stack1.empty()) {
  27. stack2.push(stack1.pop());
  28. }
  29. }
  30. }

源码分析

将栈1作为原始栈,将栈1元素压入栈2是公共方法,故写成一个私有方法。

复杂度分析

视连续 push 的元素而定,时间复杂度近似为 O(1).

Reference