代码随想录算法训练Day10|LeetCode323-用栈实现队列、LeetCode 225-用队列实现栈

理论基础

栈与队列理论基础

栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 不像是set 或者map 提供迭代器iterator来遍历所有元素。

栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。

用栈实现队列

题目描述

力扣323-用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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 操作)

解题思路

使用栈来模式队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,这里要注意输入栈和输出栈的关系。

在这里插入图片描述

在push(将元素 x 推到队列的末尾)数据的时候,只要数据放进输入栈就好,但在pop(弹出)的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。

一旦有弹出操作那么就需要,要把入栈里的所有元素放入出栈中,若没有把所有的都放入,那么顺序会乱

最后如何判断队列为空呢?如果进栈和出栈都为空的话,说明模拟的队列为空了

自己解题

class MyQueue {

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

    // 初始化两个栈
    public MyQueue() {
        stackIn = new Stack<>(); // 负责进栈
        stackOut = new Stack<>(); // 负责出栈
    }

    // 将元素 x 推到队列的末尾
    public void push(int x) {// 队列尾添加
        stackIn.push(x);
    }

    // 从队列的开头移除并返回元素
    public int pop() {// 队头弹出
        checkstack();//先检查出栈是否为空
        return stackOut.pop();
    }

    // 返回队列开头的元素
    public int peek() {// 队头看一眼
        checkstack();
        return stackOut.peek();
    }

    // 如果队列为空(即两个栈都空就是空),返回 true ;否则,返回 false
    public boolean empty() {// 两个栈都空就是空
        return stackIn.empty() && stackOut.empty();
    }

    /*
     * 检查栈2是否为空,不为空则将全部栈1弹入栈2
     */
    public void checkstack() {
        // 如果栈2不为空,则不需要栈1弹入
        if (!stackOut.empty())
            return;
        // 如果栈2为空,则将栈1全部倒置弹入
        while (!stackIn.empty()) {
            stackOut.push(stackIn.pop());
        }
    }
}

参考解题

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. 将元素 x 推到队列的末尾 */
    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.
    如果队列为空,返回 true ;否则,返回 false 
    */
    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());
        }
    }
}

/**
 * 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();
 */

补充

Stack stack1 = new Stack<>()

初始化两个栈

    public MyQueue() {
        stackIn = new Stack<>(); // 负责进栈
        stackOut = new Stack<>(); // 负责出栈
    }

类 Stack

在这里插入图片描述

在push(将元素 x 推到队列的末尾)数据的时候,只要数据放进输入栈就好,但在pop(弹出)的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。

一旦有弹出操作那么就需要,要把入栈里的所有元素放入出栈中,若没有把所有的都放入,那么顺序会乱

最后如何判断队列为空呢?如果进栈和出栈都为空的话,说明模拟的队列为空了

用队列实现栈

题目描述

  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

力扣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 都保证栈不为空

解题思路

网页

视频

一个队列:取出来再放入,最后一个元素的前 size-1个元素弹出来再加入

自己解题

class MyStack {

    Queue<Integer> q;// Queue接口 找实现类 接口的成员方法只能是抽象方法

    public MyStack() {
        q = new LinkedList<>();// 创建LinkedList 对象//构造方法 LinkedList<Integer> q=new LinkList<>()
    }

    public void push(int x) {// 添加
        q.offer(x); // LinkedList类成员方法 offer 将指定元素添加到此列表的末尾(最后一个元素)。
    }

    public int pop() {// 移除
        for (int i = 0; i < q.size() - 1; i++) {// 除队尾的元素,都重新插入
            q.offer(q.poll()); // poll获取并移除此列表的头(第一个元素)
        }
        return q.poll();
    }

    public int top() {// 不移除
        for (int i = 0; i < q.size() - 1; i++) {// 除队尾的元素,都重新插入
            q.offer(q.poll());
        }
        int ansnum = q.peek(); // peek 获取但不移除此列表的头(第一个元素)。
        q.offer(q.poll());
        return ansnum;
    }

    public boolean empty() {
        return q.isEmpty(); // isEmpty 判断列表是否为空
    }
}

在这里插入图片描述

参考解题

使用两个 Queue 实现方法1

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); // 先放在辅助队列中
        while (!queue1.isEmpty()){
            queue2.offer(queue1.poll());
        }
        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();
    }
}

优化,使用一个 Queue 实现

class MyStack {

    Queue<Integer> queue;

    public MyStack() {
        queue = new LinkedList<>();
    }

    //每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
    public void push(int x) {
        queue.offer(x);
        int size = queue.size();
        //移动除了 A 的其它数
        while (size-- > 1)
            queue.offer(queue.poll());
    }

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

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

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

补充

  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

接口 Queue

   Queue<Integer> queue;

    public MyStack() {
        queue = new LinkedList<>();
    

在这里插入图片描述

LinkedList 是接口 Queue的一个实现类

在这里插入图片描述
LinkedList常用方法
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
ps:部分图片和代码来自代码随想录Leetcode官网

  • 13
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值