美文网首页
[每日一题]232.implement queue using

[每日一题]232.implement queue using

作者: 何学诚 | 来源:发表于2019-04-06 12:01 被阅读0次
1.这是一道使用队列去模拟堆栈的题目,感觉挺难想的。

反正我是没想到。
栈:先进后出。
队列:先进先出。

链接:https://leetcode.com/problems/implement-stack-using-queues/

225-implement-stack-using-queues.png

我们使用list模拟Queue(先进后出),append 入队,pop(0)出队
这里,采用一个队列实现。每次删除前面的值,添加值后面

大致过程就是这样:

225-implement-stack-using-queues.png
2.题解:
class MyStack(object):

    def __init__(self):
        self.qeque_ = []

    def push(self, x):
        self.qeque_.append(x)

    def pop(self):
        # 每次删除前面的值,添加值后面
        for i in range(len(self.qeque_) - 1):
            self.qeque_.append(self.qeque_.pop(0))
        return self.qeque_.pop(0)


    def top(self):
        for i in range(len(self.qeque_) - 1):
            self.qeque_.append(self.qeque_.pop(0))
        val = self.qeque_.pop(0)
        self.qeque_.append(val)
        return val

    def empty(self):
        if len(self.qeque_) == 0:
            return True
        else:
            return False
3.完整代码

查看链接:
https://github.com/Wind0ranger/LeetcodeLearn/blob/master/2-stack-quque/225-implement-stack-using-queues.py

相关文章

网友评论

      本文标题:[每日一题]232.implement queue using

      本文链接:https://www.haomeiwen.com/subject/jqkriqtx.html