Implement Stack using Queues

这题是使用队列去实现栈,属于比较基础的题目。需要考虑的点在于队列为先进先出,即入队在队尾,但是出队在队首,而栈为先进后出,即出栈和入栈都在栈尾。需要实现的功能如下:

push(x) -- Push element x onto stack.

pop() -- Removes the element on top of the stack.

top() -- Get the top element.

empty() -- Return whether the stack is empty.

我的解法一,python使用collections.deque()

class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.queue = collections.deque()
        

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

    def pop(self):
        """
        :rtype: nothing
        """
        i = len(self.queue)-1
        while i > 0:
            self.queue.append(self.queue.popleft())
            i-=1
        self.queue.popleft()
            

    def top(self):
        """
        :rtype: int
        """
        size=len(self.queue)
        return self.queue[size-1]
        

    def empty(self):
        """
        :rtype: bool
        """
        return len(self.queue)==0
        

这种解法其中push复杂度为O(1),pop,top,empty复杂度都为为O(n),属于比较不理想的解法。

参考一些优质解法,一个非常巧妙的思路逆序存储。具体做法为:在push元素之后,对queue中已有的元素做一个queue长度n-1次的右旋转, 相当于rotate(len(queue)-1),相当于将该元素插入在了队首。而从一开始push()就如此操作,相当于每次push之后,queue中的元素都保持原有的元素的逆序。从而使pop和top操作都为O(1),只有empty和push操作都为O(n).代码如下:

class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.queue = collections.deque()
        

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.queue.append(x)
        i=len(self.queue)-1
        while i > 0:
            self.queue.append(self.queue.popleft())
            i-=1

    def pop(self):
        """
        :rtype: nothing
        """
        self.queue.popleft()
            

    def top(self):
        """
        :rtype: int
        """
        return self.queue[0]
        

    def empty(self):
        """
        :rtype: bool
        """
        return len(self.queue)==0
原文地址:https://www.cnblogs.com/sherylwang/p/5373017.html