美文网首页
用两个栈实现一个队列

用两个栈实现一个队列

作者: 怎样会更好 | 来源:发表于2018-10-31 14:05 被阅读0次

    题目:

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

    Stack<Integer> stack1 = new Stack<Integer>();
       Stack<Integer> stack2 = new Stack<Integer>();
       
       public void push(int node) {
                  if (stack2.isEmpty()) {
               stack2.push(node);
               return;
           }
           while (!stack2.empty()) {
               stack1.push(stack2.pop());
           }
           stack2.push(node);
           while (!stack1.empty()) {
               stack2.push(stack1.pop());
           }
       }
       
       public int pop() {
       return stack2.pop();
       }
    

    关键在于有一个栈始终要保持一个出栈顺序和队列一致

    相关文章

      网友评论

          本文标题:用两个栈实现一个队列

          本文链接:https://www.haomeiwen.com/subject/sflatqtx.html