题目

大意是使用queue队列(仅用标准操作)来实现stack的操作。
225. Implement Stack using Queues

我的代码

主要思路:使用了双端队列,但默认屏蔽一些功能。使用了popleft() 和append()来实现。

class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue=collections.deque()
    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        temp=[]
        while self.queue:
            temp.append(self.queue.popleft())
        self.queue.append(x)
        for item in temp:
            self.queue.append(item)
            
        

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.queue.popleft()

    def top(self) -> int:
        """
        Get the top element.
        """
        return self.queue[0]

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return len(self.queue)==0

优秀代码(使用类似rotate()方法)

class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.q = collections.deque()

    def push(self, x: 'int') -> 'None':
        """
        Push element x onto stack.
        """
        self.q.append(x)
        i, l = 0, len(self.q)
        if (l > 1):
            while (i < l-1):
                self.q.append(self.q.popleft())
                i += 1
        

    def pop(self) -> 'int':
        """
        Removes the element on top of the stack and returns that element.
        """
        if (len(self.q) > 0): return self.q.popleft()
        return None
        

    def top(self) -> 'int':
        """
        Get the top element.
        """
        if (len(self.q) > 0): return self.q[0]
        return None
        

    def empty(self) -> 'bool':
        """
        Returns whether the stack is empty.
        """
        return len(self.q) == 0


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

相关文章: