zoukankan      html  css  js  c++  java
  • 剑指Offer:面试题7——用两个栈实现队列(java实现)

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

    首先定义两个栈

    Stack<Integer> stack1 = new Stack<Integer>();//作为进队的端口
    Stack<Integer> stack2 = new Stack<Integer>();//作为出对的端口

    思路:两个栈,有两个端口,那么肯定一个是用来入队的,另一个用来出队的。同时,由于栈是先进后出的,那么经过两次的入栈则会变为先进先出,即,第一次先进后出,第二次后进先出,两个加起来就变成了先进先出。

    故,入队时,
    为了保证队中的元素在当前元素之前,我们先从s2出栈,进入s1.

    具体看代码:很简单

    public void push(int node) {
            //检查是否满了?
    
    
    
            //将s2中的元素出栈,进栈到s1中
            while(!stack2.isEmpty()){
                int x = stack2.pop();
                stack1.push(x);
            }
    
            //node元素进栈
            stack1.push(node);
    
            //stack1中全体元素出栈,进入stack2中
            while(!stack1.isEmpty()){
                int x = stack1.pop();
                stack2.push(x);
            }
        }
    
      public int pop() {
    
        if(!stack2.isEmpty()){
            int x = stack2.pop();
            return x;
        }else{
            return -1;
        }
       }

    当然这是从进队入手,出队简化。反之,我们也可以简化入队而让出队时考虑到应有情况。代码如下:

    public void push(int node) {
            stack1.push(node);
        }
    
       public int pop() {
    
        //检查s2是否为空
        if(stack2.isEmpty()){
            //从stack1弹出元素并压入stack2
            while(!stack1.isEmpty()){
                int x = stack1.pop();
                stack2.push(x);
            }
    
    
        }
    
        //出队
        int head = stack2.pop();
        return head;
       }

    相比之下,第二个方法更简单一些。

  • 相关阅读:
    Timer定时任务
    spring boot配置多数据源
    消费者模块调用提供者集群报错
    修改windHost文件
    spring常用注解+Aop
    添加ClustrMaps
    无题
    2020年3月21日 ICPC训练联盟周赛,Benelux Algorithm Programming Contest 2019
    2020年3月14日 ICPC训练联盟周赛,Preliminaries for Benelux Algorithm Programming Contest 2019
    2020.4.12 个人rating赛 解题+补题报告
  • 原文地址:https://www.cnblogs.com/wenbaoli/p/5655727.html
Copyright © 2011-2022 走看看