【Leetcode-python】栈和队列题II

【Leetcode-python】栈和队列题II_第1张图片

class MyStack(object):
    """
    双向列表实现,为什么push时候使用q更快?此方法36ms,注释方法20ms
    """
    def __init__(self):
        self._queue = collections.deque()

    def push(self, x):
        # q = self._queue
        # q.append(x)
        # for _ in range(len(q) - 1):
        #     q.append(q.popleft())
        self._queue.append(x)
        for _ in range(len(self._queue) - 1):
            self._queue.append(self._queue.popleft())

    def pop(self):
        return self._queue.popleft()

    def top(self):
        return self._queue[0]

    def empty(self):
        return not len(self._queue)

 

【Leetcode-python】栈和队列题II_第2张图片

class MyQueue(object):
    """
    思路:利用两个stack实现。
    push:直接存入stack_1中
    pop:由于stack_1 pop栈顶元素(即后进入的元素),故将stack_1元素存入stack_2中,此时
    stack_2栈顶为先进入的元素,pop即实现先进先出
    peek:此时需要思考清楚,到底哪个是队首元素
    假设如果我们没进行pop操作,则只有stack_1有元素,队首stack[0]
    但是进行了pop操作,则队首元素一定在stack_2,且在栈顶stack[-1]
    看了一下别人的方法,大同小异
    """
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack_1,self.stack_2 = [],[]


    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.stack_1.append(x)

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        self.peek()
        return self.stack_2.pop()
        """
        if self.stack_2 is None:
            while self.stack_1:
                self.stack_2.append(self.stack_1.pop())
        res = self.stack_2.pop()
        return res


    def peek(self):
        """
        Get the front element.
        :rtype: int
        if not self.stack_2:
            while self.stack_1:
                self.stack_2.append(self.stack_1.pop())
        return self.stack_2[-1]
        """
        return self.stack_1[0]


    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return not self.stack_1 and not self.stack_2

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

 

你可能感兴趣的:(数据结构与算法)