训练营一期day10

对于栈和队列的概念不是了解,所以答案直接用的代码随想录的。之后还需要再复习。

具体差别:知了好学-专业教育培训服务平台

# 232.用栈实现队列

- 链接:栈的基本操作! | LeetCode:232.用栈实现队列_哔哩哔哩_bilibili

- 答案:

class MyQueue(object):

    def __init__(self):
        self.stack_in = []
        self.stack_out = []


    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.stack_in.append(x)


    def pop(self):
        """
        :rtype: int
        """
        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):
        """
        :rtype: int
        """
        ans = self.pop()
        self.stack_out.append(ans)
        return ans


    def empty(self):
        """
        :rtype: bool
        """
        return not (self.stack_in or self.stack_out)

# 225.用队列实现栈

- 链接:队列的基本操作! | LeetCode:225. 用队列实现栈_哔哩哔哩_bilibili

- 答案:

class MyStack(object):

    def __init__(self):
        self.queue_in = deque()
        self.queue_out = deque()


    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.queue_in.append(x)


    def pop(self):
        """
        :rtype: int
        """
        if self.empty():
            return None

        for i in range(len(self.queue_in) - 1):
            self.queue_out.append(self.queue_in.popleft())
        
        self.queue_in, self.queue_out = self.queue_out, self.queue_in    # 交换in和out,这也是为啥in只用来存
        return self.queue_out.popleft()


    def top(self):
        """
        :rtype: int
        """
        if self.empty():
            return None
        
        return self.queue_in[-1]


    def empty(self):
        """
        :rtype: bool
        """
        return len(self.queue_in) == 0

deque():

python中deque模块详解_吃鱼的羊的博客-CSDN博客_deque python

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值