当前位置: 首页 > article >正文

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

题目

用栈来实现队列

思路1

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

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

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

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出队。

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;
    }
}

http://www.kler.cn/news/316566.html

相关文章:

  • Python 类class的用法详解
  • 渗透测试综合靶场 DC-2 通关详解
  • comfyui中报错 Cmd(‘git‘) failed due to: exit code(128) 如何解决
  • 【医疗大数据】医疗保健领域的大数据管理:采用挑战和影响
  • 【2025】中医药健康管理小程序(安卓原生开发+用户+管理员)
  • 计算机毕业设计推荐-基于python的白酒销售数据可视化分析
  • 828华为云征文 | 构建高效搜索解决方案,Elasticsearch Kibana的完美结合
  • 计算结构力学,平行桁架杆件轴力计算源程序
  • Spring IoC 注解 总结
  • vue是如何优化
  • 【C++算法】分治——快排
  • 力扣(leetcode)每日一题 2374 边积分最高的节点
  • 神经生物学精解【2】
  • LeetCode[中等]
  • 迷雾大陆免费辅助:强流派推荐攻略!VMOS云手机自动辅助挂机教程!
  • [JavaEE] TCP协议
  • hql杂谈一
  • 黑马智数Day3
  • C#设计模式之备忘录模式
  • CMake 构建Qt程序弹出黑色控制台
  • vue3+ant design vue 中弹窗自定义按钮设置及以冒号为基准布局
  • IM项目-----语音识别子服务
  • Java笔试面试题AI答之设计模式(4)
  • 进击J7:对于ResNeXt-50算法的思考
  • [深度学习]Pytorch框架
  • 猿大师办公助手在线编辑Office为什么要在客户端电脑安装插件微软Office或金山WPS?
  • 政务安全体系构建中的挑战
  • 使用思科搭建企业网规划训练,让网络全部互通,使用规则提高工作效率。
  • 深入解析数据库DQL语言:查询的艺术
  • 如何在SpringCloud中使用Consul进行服务发现与配置管理