代码随想录算法训练营第10天|232. 用栈实现队列 225. 用队列实现栈

JAVA代码编写

232. 用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

  • 只能 使用标准的栈操作 ------ 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

示例 1:

复制代码
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

提示:

  • 1 <= x <= 9
  • 最多调用 100pushpoppeekempty
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

进阶:

  • 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

教程:https://programmercarl.com/0232.用栈实现队列.html#算法公开课

解:

思路:队列由两个栈表示:进栈stackIn、出栈stackOut

  • 队列进队push:等价于直接进栈

  • 队列出队pop:将stackIn中出栈到stackOut中,然后再出栈

    • dumpstackIn()函数:将stackIn中出栈到stackOut中
  • 返回队列底元素(最先入队的元素):相当岁返回stackOut的栈顶元素

  • 队列是否为空:为空的话,就是要stackIn和stackOut都为空

java 复制代码
import java.util.Stack;

class MyQueue {

    Stack<Integer> stackIn;
    Stack<Integer> stackOut;

    /** Initialize your data structure here. */
    public MyQueue() {
        stackIn = new Stack<>(); // 负责进栈
        stackOut = new Stack<>(); // 负责出栈
    }

    /** Push element x to the back of queue.入队 */
    public void push(int x) {
        stackIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. 删除该队列元素,删第一个进队列的*/
    public int pop() {
        dumpstackIn();
        return stackOut.pop();
    }

    /** Get the front element. 返回队列底元素:最先入队的元素*/
    public int peek() {
        dumpstackIn();
        return stackOut.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }

    // 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
    private void dumpstackIn(){
        if (!stackOut.isEmpty()) return;
        while (!stackIn.isEmpty()){
            stackOut.push(stackIn.pop());
        }
    }

    public static void main(String[] args) {
        MyQueue myQueue= new MyQueue();
        myQueue.push(1);
        myQueue.push(2);
        myQueue.push(3);
        myQueue.push(4);
        myQueue.pop();
        myQueue.push(5);
        myQueue.push(6);
        System.out.println(myQueue.peek());
    }
}

225. 用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

注意:

  • 你只能使用队列的基本操作 ------ 也就是 push to backpeek/pop from frontsizeis empty 这些操作。
  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例:

复制代码
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

提示:

  • 1 <= x <= 9
  • 最多调用100pushpoptopempty
  • 每次调用 poptop 都保证栈不为空

**进阶:**你能否仅用一个队列来实现栈。

教程:https://programmercarl.com/0225.用队列实现栈.html

解:

思路:栈由两个队列表示:queue1、queue2

  • 进栈push:将元素,进队到queue2;当queue1不是空的时候,将queue1出队的元素入队到queue2;再交换queue1和queue2
java 复制代码
import java.util.LinkedList;
import java.util.Queue;



class MyStack {

    Queue<Integer> queue1; // 和栈中保持一样元素的队列
    Queue<Integer> queue2; // 辅助队列

    /** Initialize your data structure here. */
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    /** Push element x onto stack. 入栈*/
    public void push(int x) {
        queue2.offer(x); // 先放在辅助队列中,offer:元素入队
        while (!queue1.isEmpty()){
            queue2.offer(queue1.poll());//poll:移除并返回队列头部的元素
            //逆序存入queue2
        }
        Queue<Integer> queueTemp;
        queueTemp = queue1;
        queue1 = queue2;
        queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可
    }

    /** Get the top element. */
    public int top() {
        return queue1.peek();
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue1.isEmpty();
    }

    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        myStack.pop();
        myStack.push(4);

    }
}
相关推荐
洛水水5 小时前
【力扣100题】18.随机链表的复制
算法·leetcode·链表
南宫萧幕5 小时前
规则基 EMS 仿真实战:SOC 区间划分与 Simulink 闭环建模全解
算法·matlab·控制
多加点辣也没关系5 小时前
数据结构与算法|第二十三章:高级数据结构
数据结构·算法
庞轩px6 小时前
第七篇:Spring扩展点——如何优雅地介入Bean的创建流程
java·后端·spring·bean·aware·扩展点
代钦塔拉6 小时前
Qt4 vs Qt5 带参数信号槽的连接方式详解
开发语言·数据库·qt
tongluowan0078 小时前
一个请求在Spring MVC 中是怎么流转的
java·spring·mvc
hoiii1878 小时前
孤立森林 (Isolation Forest) 快速异常检测系统
算法
夜郎king8 小时前
Spring AI 对接大模型开发易错点总结与实战解决办法
java·人工智能·spring
InfinteJustice8 小时前
踩坑分享C 语言文件操作全攻略:从基础读写到随机访问与缓冲区原理
c语言·开发语言·microsoft
码云数智-大飞8 小时前
滥用Lombok的@EqualsAndHashCode导致线上事故复盘
开发语言