剑指offer 5.用两个栈实现队列

5.用两个栈实现队列

题目

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路

栈是先进后出,队列是先进先出,两个栈,那么负负得正,就可以得到先进先出。
入栈就直接使用第一个栈,栈内关系有序,出栈时,若第二个栈为空,就将第一个栈转移到第二个栈,先进第一个栈后出第一个栈后进第二个栈,先出第一个栈,方向调过来了。若第二个栈不为空,那就输出第二个栈的顶端,顺序一样的。

代码

  Stack<Integer> stack1 = new Stack<Integer>();
  Stack<Integer> stack2 = new Stack<Integer>();

  public void push(int node) {
    stack1.push(node);
  }

  public int pop() {
    if (stack2.empty()) {
      while (!stack1.empty()) {
        int temp = stack1.pop();
        stack2.push(temp);
      }
    }
    int temp = stack2.peek();
    stack2.pop();
    return temp;
  }
原文地址:https://www.cnblogs.com/blogxjc/p/12367172.html