Skip to content

Latest commit

 

History

History
53 lines (44 loc) · 1.28 KB

0225._implement_stack_using_queues.md

File metadata and controls

53 lines (44 loc) · 1.28 KB

Navigation

Links:

  1. https://leetcode.com/problems/implement-stack-using-queues/
  2. https://leetcode-cn.com/problems/implement-stack-using-queues/

Solution 1 一个队列

每次新元素进队列的时候,先把当前的数字进入队列,然后把它前面的所有的元素翻转一下,翻到了它的后面。

class MyStack:

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

    def push(self, x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: void
        """
        self.que.append(x)
        for i in range(len(self.que) - 1):
            self.que.append(self.que.popleft())
            
    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        :rtype: int
        """
        return self.que.popleft()
    
    def top(self):
        """
        Get the top element.
        :rtype: int
        """
        return self.que[0]

    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        return not self.que