美文网首页
剑指offer题解之五——用两个栈实现队列

剑指offer题解之五——用两个栈实现队列

作者: KaelQ | 来源:发表于2016-08-24 13:52 被阅读106次

1.题目概述

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

2.解题思路

  • 队列是先进后出,栈是先进先出。
    那么使用两个堆栈进行模拟即可。


3.代码解释

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
     
    public void push(int node) {//push为正常的堆栈push
         stack1.push(new Integer(node));
    }
 
    public int pop() {
       if(stack2.empty()){ //如果stack2为空,stack1就全部出栈到stack2中。
           while(!stack1.empty()){
               stack2.push(stack1.pop());
           }
       }
       if(stack2.empty()){//stack1出栈到stack2中后依然为空,证明此时队列为空。
             System.out.println("队列为空");
       }  
       return stack2.pop().intValue();
 }
}

相关文章

网友评论

      本文标题:剑指offer题解之五——用两个栈实现队列

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