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

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();
 }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容