【百日算法计划】:每日一题,见证成长(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;
    }
}
相关推荐
C雨后彩虹4 分钟前
Java 并发程序性能优化:思路、方法与实践
java·线程·多线程·并发
!停6 分钟前
数据结构空间复杂度
java·c语言·算法
一路往蓝-Anbo7 分钟前
第 4 篇:策略模式 (Strategy) —— 算法的热插拔艺术
网络·驱动开发·stm32·嵌入式硬件·算法·系统架构·策略模式
她说..8 分钟前
验签实现方案整理(签名验证+防篡改+防重放)
java·经验分享·spring boot·java-ee·bladex
不染尘.10 分钟前
二分算法(优化)
开发语言·c++·算法
不吃橘子的橘猫11 分钟前
Verilog HDL基础(概念+模块)
开发语言·学习·算法·fpga开发·verilog
爱吃山竹的大肚肚13 分钟前
异步导出方案
java·spring boot·后端·spring·中间件
苦藤新鸡14 分钟前
49.二叉树的最大路径和
数据结构·算法·深度优先
源代码•宸16 分钟前
Leetcode—144. 二叉树的前序遍历【简单】
经验分享·算法·leetcode·面试·职场和发展·golang·dfs
没有bug.的程序员21 分钟前
Spring Boot 与 Redis:缓存穿透/击穿/雪崩的终极攻防实战指南
java·spring boot·redis·缓存·缓存穿透·缓存击穿·缓存雪崩