美文网首页北美程序员面试干货
LeetCode 232 [Implement Queue us

LeetCode 232 [Implement Queue us

作者: Jason_Yuan | 来源:发表于2016-06-27 08:12 被阅读18次

原题

正如标题所述,你需要使用两个栈来实现队列的一些操作。
队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。
pop和top方法都应该返回第一个元素的值。

样例
比如push(1), pop(), push(2), push(3), top(), pop(),
你应该返回1,2和2

解题思路

  • 使用两个stack就可以实现queue的API
  • 每次push就push到stack1
  • 每次pop或者top,则看stack2是否为空,若为空,则将stack1中的元素pop出来并push到stack2
stack1 = [1, 2, 3]
pop 3
stack2 = [3]
pop 2
stack2 = [3, 2]
pop 1
stack2 = [3, 2, 1] #真正的pop/top操作在stack2上执行

完整代码

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack1 = []
        self.stack2 = []
        

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.stack1.append(x)
        

    def pop(self):
        """
        :rtype: nothing
        """
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()
        

    def peek(self):
        """
        :rtype: int
        """
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]
        

    def empty(self):
        """
        :rtype: bool
        """
        return len(self.stack1) == 0 and len(self.stack2) == 0

相关文章

网友评论

    本文标题:LeetCode 232 [Implement Queue us

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