边工作边刷题:70天一遍leetcode: day 65-1

Implement Stack using Queues

要点:因为queue的是FIFO,所以要用2个queue配合来实现LIFO。2种方法:push O(1) or pop O(1)。基本思路就是如果push O(1),那么queue中的元素还是FIFO,pop的时候调整。而pop O(1),在push的时候就要调整为LIFO顺序。具体来说,

  • push O(1):假设一个q用来存所有元素,当前共n个,那么最后一个元素就是要pop的元素,只需要把其他n-1个元素再顺序pop/push到同一个q里,pop后,q还保持LIFO。这里似乎一个q就够了,其实有个trick:如果call top,元素是不pop的,如果还用同样方法,那么q就不是LIFO了。所以要用到另一个q2,每次push都到这个q2里,q2最多一个元素,如果push的时候q2里已经有元素,那么先把这个元素push到队列q中。top/pop的时候,如果q2中有元素,q2中的元素就是所求,否则把q1中多出的元素放到q2里
  • pop O(1):这个逻辑相对简单:两个q中总有一个为空作为临时周转用。每次push的时候,先push到空q中,然后把非空q中的元素push到另一个q中。因为非空q的元素总是LIFO顺序,queue push能保持这个顺序。

错误点:

  • pop O(1)中pop序列是pop第一个元素,如果python中用list模拟queue,应该是pop(0)而不是pop()。
class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.q1 = []
        self.q2 = []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        if not self.q1:
            self.q1.append(x)
            while self.q2:
                self.q1.append(self.q2.pop(0))
        else:
            self.q2.append(x)
            while self.q1:
                self.q2.append(self.q1.pop(0))

    def pop(self):
        """
        :rtype: nothing
        """
        print self.q1,self.q2
        if self.q1:
            return self.q1.pop(0)
        else:
            return self.q2.pop(0)
        

    def top(self):
        """
        :rtype: int
        """
        if self.q1:
            return self.q1[0]
        else:
            return self.q2[0]

    def empty(self):
        """
        :rtype: bool
        """
        return not (self.q1 or self.q2)
        
原文地址:https://www.cnblogs.com/absolute/p/5690348.html