天天看點

力扣(leetcode) 232. 用棧實作隊列 (兩個棧實作隊列)

題目在這:​​https://leetcode-cn.com/problems/implement-queue-using-stacks/​​

思路分析:

用兩個棧實作隊列操作,元素先進A棧,再進B棧,再彈出 即可實作先進先出的效果。

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 not self.stack2: # B棧為空
            while self.stack1: # A棧不為空
                self.stack2.append(self.stack1.pop()) # 将A棧全加到B棧中
        return self.stack2.pop()

    def peek(self) -> int:
        """
        Get the front element.
        """
        if not self.stack2: # 操作同pop()
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return  not self.stack1 and not self.stack2



# 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()