首页 > 其他分享 >【队列】LeetCode 225. 用队列实现栈

【队列】LeetCode 225. 用队列实现栈

时间:2023-01-03 19:33:21浏览次数:58  
标签:ConcurrentLinkedQueue 队列 mainQueue public int 225 assistantQueue LeetCode

题目链接

225. 用队列实现栈

思路

设置一个主队列 mainQueue 和一个辅助队列 assistantQueue,在进行压栈的时候,将 mainQueue 中的元素全部放入 assistantQueue 中,再将 x 压栈,然后再将 assistantQueue 的元素放入 mainQueue 中。

代码

class MyStack{

    ConcurrentLinkedQueue<Integer> mainQueue;
    ConcurrentLinkedQueue<Integer> assistantQueue;

    public MyStack(){

        this.mainQueue = new ConcurrentLinkedQueue<>();
        this.assistantQueue = new ConcurrentLinkedQueue<>();
    }

    public void push(int x){

        if(mainQueue.isEmpty()){
            mainQueue.add(x);
        }else{
            assistantQueue.addAll(mainQueue);
            mainQueue.clear();
            mainQueue.add(x);
            mainQueue.addAll(assistantQueue);
            assistantQueue.clear();
        }
    }

    public int pop(){
        return mainQueue.poll();
    }

    public int top(){
        return mainQueue.peek();
    }

    public boolean empty(){
        return mainQueue.isEmpty();
    }
}

拓展

【队列】LeetCode 232. 用栈实现队列

标签:ConcurrentLinkedQueue,队列,mainQueue,public,int,225,assistantQueue,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17023184.html

相关文章

  • Leetcode[LeetCode]4 两个有序数组的中位数
    上图为剑指Offer之字符串的排列,基于回溯法的思想。简单算法01数组中第二大的数02合并排序链表03链表反转04判断链表环05两个链表的首个交点06数组中出现大与一般的数07手写......
  • 【链表】LeetCode 328. 奇偶链表
    题目链接328.奇偶链表思路根据题意,我们只需要将扫描到的索引为奇数的结点不断插入到正确位置。比如1->2->3->4->5==》1->3->2->4->5==》1->3->5->2->4在扫描过......
  • 消息队列:第五章:RabbitMQ的使用
    第一步:使用之前先安装好RabbitMQ,建议安装在linux系统下安装配置RabbitMQ:https://blog.csdn.net/qq_33450681/article/details/85339315第二步:在配置文件下配置rabbitmq:......
  • [LeetCode]014-最长公共前缀
    >>>传送门题目编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串""。示例示例1输入:strs=["flower","flow","flight"]输出:"fl"......
  • 【链表】LeetCode 92. 反转链表 II
    题目链接92.反转链表II思路和【链表】LeetCode206.反转链表的思路一样,只不过需要调整一下realHead头结点的位置,同时原题中的null在本题中为rightNode的下一个结点。......
  • Redis实现消息队列
    异步消息队列说道消息队列,你肯定会想到Kafka、Rabbitmq等消息中间件,这些专业的消息中间件提供了很多功能特性,当然他的部署使用维护都是比较麻烦的。如果你对消息队列没那......
  • leetcode-637. 二叉树的层平均值
    637.二叉树的层平均值-力扣(Leetcode)层次遍历+求平均值,Go中的切片也可以模拟queue的功能/***Definitionforabinarytreenode.*typeTreeNodestruct{*......
  • kafka学习笔记03消息队列的两种模式
     ①点对点模式  该种模式就是消费者会自动消费消息,消息收到之后会向消息队列进行确认收到消息,然后将该数据进行删除。 ②发布/订阅模式  可以有多个的topic,topic......
  • LeetCode每日一题1.3
    2042.CheckifNumbersAreAscendinginaSentencehttps://leetcode.cn/problems/check-if-numbers-are-ascending-in-a-sentence......
  • LeetCode每日一题1.1
    2351.FirstLettertoAppearTwiceGivenastring\(s\)consistingoflowercaseEnglishletters,returnthefirstlettertoappeartwice.Note:Aletter\(a\)......