Leedcode【225】:用队列实现栈,两种解法

题目:

 

解法一:

from queue import Queue

class MyStack:
    # 思路一:
    #     1.初始化一个队列为空,每次pop把另一个队列前n-1个元素,移动到为空的队列,然后输出最后一个元素,即为栈顶元素;一轮操作过后需要交换输入输出队列
    #     2.push时,把最新进队列的元素标记为栈顶元素

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.input_que = Queue()
        self.out_que = Queue()

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.input_que.put(x)
        self.top_e = x
        
    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        while (self.input_que.qsize() > 1):
            self.top_e = self.input_que.get()  # 比如1,2,3依次入队列,当3被pop后,2就是栈顶元素
            self.out_que.put(self.top_e)
        top = self.input_que.get()
        self.input_que, self.out_que = self.out_que, self.input_que
        return top

    def top(self) -> int:
        """
        Get the top element.
        """
        return self.top_e

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return self.input_que.empty() and self.out_que.empty()




 

解法二:

from queue import Queue

class MyStack:

    # # 思路二:使用list,反转list元素;  虽然能提交但有点问题?比如输入3个数1,2,3,经过反转后3,1,2?但leedcode上没有三个数的测试案例
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.input = []

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.input.append(x)
        k = len(self.input)
        while k>1:
            self.input.append(self.input.pop(0))
            k -= 1
        
    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.input.pop(0)


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


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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值