剑指Offer 09. 用两个栈实现队列(Easy)/ 225. 用队列实现栈(Easy)/ 栈、队列实现问题!!!

题解

  1. 用两个栈实现队列(清晰图解)

思路

在这里插入图片描述
在这里插入图片描述

代码

class CQueue:
    ### 1130 辅助栈(456 ms,17 MB)
    def __init__(self):
        # 当且仅当B中为空时,才会将A中元素全部传入B中(即若B中元素没全部出栈时,A中的元素是会持续积压的)
        self.A, self.B = [], []

    def appendTail(self, value: int) -> None:
        self.A.append(value)

    def deleteHead(self) -> int:
        # 若B中还有元素,则出栈
        if self.B: return self.B.pop()

        # 若B为空且若A为空,则返回-1
        if not self.A: return -1

        # 若B为空,但A非空,则将A中所有元素传入B,然后B出栈
        while self.A:
            self.B.append(self.A.pop())
        return self.B.pop()


# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()

225. 用队列实现栈

在这里插入图片描述

class MyStack:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue1 = collections.deque() # 用于存储栈内的元素
        self.queue2 = collections.deque() # 作为入栈操作的辅助队列

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        # 入栈操作时,首先将元素入队到queue2,
        self.queue2.append(x)
        # 再把queue1中所有元素出队加入queue2,相当于把需要Push的元素放在栈顶
        while self.queue1:
            self.queue2.append(self.queue1.popleft())
        # 交换两个队列,使得push相当于每次在前面加元素
        self.queue1, self.queue2 = self.queue2, self.queue1

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.queue1.popleft()

    def top(self) -> int:
        """
        Get the top element.
        """
        return self.queue1[0]

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return not self.queue1

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值