【每日算法】力扣232. 用栈实现队列

118 阅读2分钟

「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战」。

描述

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

实现 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(双端队列)来模拟一个栈,只要是标准的栈操作即可。  

进阶:

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

示例:

输入:
["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
 

做题

思路

想要使用栈模拟队列,最少要两个栈,因为我们需要把一个栈的数据倒出到另外一个栈,这样我们才能先进先出地会的数据。

先用 stack1 来存储进入队列的数据。

当要从队列中拿数据时,我们就把 stack1 的数据倒出到 stack2,这样就能拿到最先进入 stack1 的数据,倒出到 stack2 后,这时我们直接拿 stack2 中的数据,每次拿到的都是最先进入的数据,实现先进先出。

import java.util.*;

class MyQueue {
    Stack<Integer> stack1 = null;
    Stack<Integer> stack2 = null;


    public MyQueue() {
        stack1 = new Stack();
        stack2 = new Stack();
    }
    
    public void push(int x) {
        stack1.push(x);
    }
    
    public int pop() {
        checkoutStach();
        return stack2.pop();
    }
    
    public int peek() {
        checkoutStach();
        return stack2.peek();
    }
    
    public boolean empty() {
        return stack1.empty()&&stack2.empty();
    }

    private void checkoutStach(){
        if(stack2.empty()){
            //当 stack2 为空,把 stack1 的数据转移到 stack2
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
    }
}

image.png

最后

今天就到这里了。

这里是程序员徐小白,【每日算法】是我新开的一个专栏,在这里主要记录我学习算法的日常,也希望我能够坚持每日学习算法,不知道这样的文章风格您是否喜欢,不要吝啬您免费的赞,您的点赞、收藏以及评论都是我下班后坚持更文的动力。