【代码随想录】栈与队列篇

栈与队列之用栈实现队列



(力扣)232.用栈实现队列

https://leetcode.cn/problems/implement-queue-using-stacks/
https://leetcode.cn/problems/implement-queue-using-stacks/


1.题目分析

为了更好的理解这道题,我们假设有4个数字,如:1,2,3,4,现在我们把它放入一个栈中,而栈的特点是先进后出,所以,它的进栈出栈就类似下面这张图。这张图表达的意思是,进栈的时候,顺序是1,2,3,4,出栈的时候是4,3,2,1。
@bailu

而队列的特点是先进先出,那么题目要求用栈实现队列的形式,就应该类似下面这张图。这张图表达的意思是,再设置一个空的栈,栈一的顺序是1,2,3,4,把栈一的数字每次pop出来,放入栈二中,由于栈的特点是先进后出,取出来的数按顺序放入栈二,那么栈二的入栈顺序就会变成4,3,2,1,这时候再对栈二进行出栈,则栈二的出栈顺序就是1,2,3,4。这就实现了队列的功能,先进先出,即顺序都是1,2,3,4。
@bailu
所以,在push数据的时候,只要数据放进输入栈就好,在pop数据时,先判断栈二是否为空,如果不为空,那么就直接pop栈二,如果栈二为空,那么就先把栈一的数据全部按逆序导入栈二中,即stack2.push(stack1.pop())。要实现peek,即返回队列首部的元素,也是同样道理。

2.代码

java

class MyQueue {

    Stack<Integer> stack1;
    Stack<Integer> stack2;

    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<>(); // 负责进栈
        stack2 = new Stack<>(); // 负责出栈
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {    
        dumpstackIn();
        return stack2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        dumpstackIn();
        return stack2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    // 如果stack2为空,那么将stack1中的元素全部放到stack2中
    private void dumpstackIn(){
        if (!stack2.isEmpty()) return; 
        while (!stack1.isEmpty()){
                stack2.push(stack1.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();
 */

python

class MyQueue:

    def __init__(self):
        """
        in主要负责push,out主要负责pop
        """
        self.stack_in = []
        self.stack_out = []


    def push(self, x: int) -> None:
        """
        有新元素进来,就往in里面push
        """
        self.stack_in.append(x)


    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if self.empty():
            return None
        
        if self.stack_out:
            return self.stack_out.pop()
        else:
            for i in range(len(self.stack_in)):
                self.stack_out.append(self.stack_in.pop())
            return self.stack_out.pop()


    def peek(self) -> int:
        """
        Get the front element.
        """
        ans = self.pop()
        self.stack_out.append(ans)
        return ans


    def empty(self) -> bool:
        """
        只要in或者out有元素,说明队列不为空
        """
        return not (self.stack_in or self.stack_out)

3.自查

java里面:

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

《代码随想录》是这样定义的两个Integer泛型的Stack,也就是我题目分析的栈一和栈二,我为了方便我自己理解,改成了栈一和栈二,变量名这个东西嘛,可以自定义的,意思理解到位就好啦,而Stack是栈的类名。

python里面:

def push(self, x: int) -> None:
def pop(self) -> int:
def peek(self) -> int;
def empty(self) -> bool:

在ptyhon里面,def用来定义函数的,->所指的呢,就是返回值类型,类似Java的return。

4.引用参考

https://leetcode.cn/problems/implement-queue-using-stacks/

https://www.programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值