【剑指Offer】第8题-用栈实现队列-Python

LeetCode

232. 用栈实现队列

题目分析

栈的特点是先入后出,即最后被压入(push)栈的元素第一个弹出(pop)。
队列的特点是先入先出,即第一个进入队列的元素第一个出来。
虽然栈和队列是两个针锋相对的数据结构,但是却可以相互联系。
本题的意思是想要通过两个栈来实现队列。

通过一个具体的例子来说明往队列中插入元素的过程。首先插入一个元素a,不妨先把它插入到stack1,此时stack1中有{a}。再插入b,c到stack1中,此时stack1中有{a,b,c}。其中c位于栈顶,而stack2依然是空的。

接着删除一个元素,由于a比b,c先进入的栈,所有a应该先出队列。而a位于stack1中的底部,不能直接出栈。到了stack2发挥作用的时候,如果把stack1中的元素挨个弹出并压入到stack2中,这样元素在stack2中的顺序就和stack1中相反。这时就可以弹出stack2的顶部,而stack1为空。
【剑指Offer】第8题-用栈实现队列-Python_第1张图片

如果还想继续删除元素,可以直接从stack2中弹出栈顶。

总结出删除元素的步骤:

  • 当stack2中元素不为空,说明stack2栈顶元素是队首,直接弹出
  • 当stack1中元素为空,说明数据还没从stack1压入stack2。执行压入操作,返回stack2栈顶

接下来讨论插入元素,直接压入stack1栈顶,这样满足队列性质。

取栈顶元素和pop操作类似,不同之处在于不弹出,仅取值

判空操作就是当两个栈都为空时,就是空队列。

code

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack1 = []
        self.stack2 = []

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.stack1.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if len(self.stack2) == 0 :
            while len(self.stack1)>0:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()

    def peek(self) -> int:
        """
        Get the front element.
        """
        if len(self.stack2) == 0 :
            while len(self.stack1)>0:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        if len(self.stack2) == 0 and len(self.stack1) == 0:
            return True
        else:
            return False

你可能感兴趣的:(LeetCode,剑指offer)