【百日算法计划】:每日一题,见证成长(017)

题目

用栈来实现队列

思路1

入队直接入,出队用两个栈来回倒腾。

java 复制代码
static class StackToQueue{

    Stack<Integer> stack = new Stack<>();
    Stack<Integer> tmpStack = new Stack<>(); //临时栈

    public StackToQueue(){}

    //入队 直接入
    public void enqueue(Integer val){
        stack.push(val);
    }

    //出队
    public Integer dequeue(){

        if (stack.isEmpty()) return null;

        while (!stack.isEmpty()){
            tmpStack.push(stack.pop());
        }

        Integer pop = tmpStack.pop();
        while (!tmpStack.isEmpty()){
            stack.push(tmpStack.pop());
        }
        return pop;
    }
}

思路2

入队来回倒腾,出队直接出。

java 复制代码
static class StackToQueue2{
    Stack<Integer> stack = new Stack<>();
    Stack<Integer> tmpStack = new Stack<>(); //临时栈

    public StackToQueue2(){}

    //入队 两个栈倒腾
    public void enqueue(Integer val){
        //新元素进来时,把stack里面的元素倒腾到tmp里去
        while (!stack.isEmpty()){
            tmpStack.push(stack.pop());
        }
        stack.push(val);
        while (!tmpStack.isEmpty()){
            stack.push(tmpStack.pop());
        }
    }

    //出队
    public Integer dequeue(){
        if (stack.isEmpty()) return null;
        return stack.pop();
    }
}

思路3

倒腾到tmpStack后,不用再倒腾回去了;当tmpStack不为空的时候,直接从tmpStack出队。

java 复制代码
static class StackToQueue3{

    Stack<Integer> stack = new Stack<>();
    Stack<Integer> tmpStack = new Stack<>(); //临时栈

    public StackToQueue3(){}

    //入队 直接入
    public void enqueue(Integer val){
        stack.push(val);
    }

    //出队 优化一下
    public Integer dequeue(){

        if (stack.isEmpty() && tmpStack.isEmpty()) return -1;
        int r;
        if (!tmpStack.isEmpty()){
            r = tmpStack.pop();
        } else {
            while (!stack.isEmpty()){
                tmpStack.push(stack.pop());
            }
            r = tmpStack.pop();
        }
        return r;
    }
}
相关推荐
阳光阿盖尔6 分钟前
EasyExcel的基本使用——Java导入Excel数据
java·开发语言·excel
二十雨辰7 分钟前
[苍穹外卖]-12Apache POI入门与实战
java·spring boot·mybatis
程序员皮皮林8 分钟前
开源PDF工具 Apache PDFBox 认识及使用(知识点+案例)
java·pdf·开源·apache
蔚一8 分钟前
Java设计模式—面向对象设计原则(三) -----> 依赖倒转原则DIP(完整详解,附有代码+案例)
java·开发语言·设计模式·intellij-idea·依赖倒置原则
liang899914 分钟前
SpringSecurity原理解析(七):权限校验流程
java·开发语言
孙小二写代码15 分钟前
[leetcode刷题]面试经典150题之1合并两个有序数组(简单)
算法·leetcode·面试
little redcap21 分钟前
第十九次CCF计算机软件能力认证-1246(过64%的代码-个人题解)
算法
搁浅°87923 分钟前
IO文件拷贝
java·开发语言
Python私教26 分钟前
Python国产新 ORM 框架 fastzdp_sqlmodel 快速入门教程
java·数据库·python
Python私教27 分钟前
Python ORM 框架 SQLModel 快速入门教程
android·java·python