算法例题整理01-队列leecode225

用队列实现栈

使用队列实现栈的下列操作:

push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空

使用两个队列
使用put()将元素添加到序列尾端,get()从队列尾部移除元素

from queue import Queue


class MyStack:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue_push = Queue()
        self.queue_pop = Queue()


    def push(self, x):
        """
        Push element x onto stack.
        """
        self.queue_push.put(x)
        self.top_ele = x


    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        """
        while (self.queue_push.qsize() > 1):
            self.top_ele = self.queue_push.get()
            self.queue_pop.put(self.top_ele)
        res = self.queue_push.get()
        self.queue_pop, self.queue_push = self.queue_push, self.queue_pop
        return res


    def top(self):
        """
        Get the top element.
        """
        return self.top_ele


    def empty(self):
        """
        Returns whether the stack is empty.
        """
        #return self.queue_push.empty() and self.queue_pop.empty()
        return self.in_que.qsize() + self.out_que.qsize() == 0

#have a try
stack = MyStack()
stack.push(-2)
stack.push(0)
stack.push(-3)
stack.push(5)
stack.push(-4)
print('栈中所有元素:',stack)
stack.pop()
print('栈顶元素:',stack.top())
stack.pop()
print('栈顶元素:',stack.top())
stack.pop()
print('栈顶元素:',stack.top())
stack.pop()
print('栈顶元素:',stack.top())
stack.pop()
print('栈顶元素:',stack.top())
stack.empty()
print('栈顶元素:',stack.empty())

执行用时 :28 ms, 在所有 Python3 提交中击败了88.13%的用户

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值