jz3.用两个栈实现一个队列

169 阅读1分钟

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

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    //即便在pop之后,又有新的进来,也是要先把旧的pop完了,下次stack2是空的,还是从stack1里面循环放进来。
    public int pop() {
      if(stack2.isEmpty()){
          if(stack1.isEmpty()){
              return 0;
          }
          while(!stack1.isEmpty()){
              stack2.push(stack1.pop());
          }
      }
      return stack2.pop();
    }
}