【算法刷题day9】Leetcode:232.用栈实现队列、225. 用队列实现栈

文章目录

草稿图网站
java的Deque

Leetcode 232.用栈实现队列

题目: 232.用栈实现队列
解析: 代码随想录解析

解题思路

一个栈负责进,一个栈负责出

代码

java 复制代码
class MyQueue {
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;


    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        dumpStackIn();
        return stackOut.pop();
    }
    
    public int peek() {
        dumpStackIn();
        return stackOut.peek();
    }
    
    public boolean empty() {
        if (stackOut.isEmpty() && stackIn.isEmpty())
            return true;
        return false;
    }
    public void dumpStackIn(){
        if (!stackOut.isEmpty())
            return;
        while(!stackIn.isEmpty()){
            stackOut.push(stackIn.pop());
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

总结

暂无

Leetcode 225. 用队列实现栈

题目: 225. 用队列实现栈
解析: 代码随想录解析

解题思路

每次使用一个辅助队列来存储后入元素,然后把队列元素插入辅助队列中,再对换索引。

代码

java 复制代码
class MyStack {

    Queue<Integer> queue1;
    Queue<Integer> queue2;

    public MyStack() {
       queue1 = new LinkedList<>();
       queue2 = new LinkedList<>();
    }
    
    public void push(int x) {
        queue2.offer(x);
        while(!queue1.isEmpty()){
            queue2.offer(queue1.poll());
        }
        Queue<Integer> queueTmp = queue1;
        queue1 = queue2;
        queue2 = queueTmp;
    }
    
    public int pop() {
        return queue1.poll();
    }
    
    public int top() {
        return queue1.peek();
    }
    
    public boolean empty() {
        return queue1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

总结

暂无

stack、queue和deque对比


相关推荐
多米Domi0118 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
罗湖老棍子9 小时前
【例4-11】最短网络(agrinet)(信息学奥赛一本通- P1350)
算法·图论·kruskal·prim
方圆工作室9 小时前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
Lips6119 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
kylezhao201910 小时前
C# 文件的输入与输出(I/O)详解
java·算法·c#
CodeByV10 小时前
【算法题】堆
算法
kaikaile199510 小时前
A星算法避开障碍物寻找最优路径(MATLAB实现)
数据结构·算法·matlab
今天_也很困11 小时前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode
企业对冲系统官11 小时前
基差风险管理系统日志分析功能的架构与实现
大数据·网络·数据库·算法·github·动态规划
ldccorpora11 小时前
GALE Phase 1 Chinese Broadcast News Parallel Text - Part 1数据集介绍,官网编号LDC2007T23
人工智能·深度学习·算法·机器学习·自然语言处理