【百日算法计划】:每日一题,见证成长(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;
    }
}
相关推荐
云惠科技(SEO)2 分钟前
泛目录站群技术架构演进观察:2025年PHP+Java混合方案实战笔记
java·人工智能·搜索引擎
coder777711 分钟前
js逆向分享
javascript·爬虫·python·算法·安全
冠位观测者33 分钟前
【Leetcode 每日一题 - 补卡】1534. 统计好三元组
数据结构·算法·leetcode
牛马baby38 分钟前
Springboot 自动装配原理是什么?SPI 原理又是什么?
java·spring boot·后端
明月看潮生38 分钟前
青少年编程与数学 02-016 Python数据结构与算法 25课题、量子算法
python·算法·青少年编程·量子计算·编程与数学
小小深1 小时前
了解JVM
java·jvm
Sunlight_7771 小时前
第五章 SQLite数据库:1、SQLite 基础语法及使用案例
java·linux·服务器·jvm·数据库·tcp/ip·sqlite
JNU freshman1 小时前
C. Robin Hood in Town思考与理解
算法
JhonKI1 小时前
【从零实现高并发内存池】内存池整体框架设计 及 thread cache实现
java·redis·缓存
何似在人间5751 小时前
SpringAI+DeepSeek大模型应用开发——4 对话机器人
java·机器人·大模型应用开发·spring ai