LeetCode 232 [Implement Queue using Stacks]

原題

正如標題所述,你需要使用兩個棧來實現隊列的一些操作。
隊列應支持push(element),pop() 和 top(),其中pop是彈出隊列中的第一個(最前面的)元素。
pop和top方法都應該返回第一個元素的值。

樣例
比如push(1), pop(), push(2), push(3), top(), pop(),
你應該返回1,2和2

解題思路

  • 使用兩個stack就可以實現queue的API
  • 每次push就push到stack1
  • 每次pop或者top,則看stack2是否為空,若為空,則將stack1中的元素pop出來并push到stack2
stack1 = [1, 2, 3]
pop 3
stack2 = [3]
pop 2
stack2 = [3, 2]
pop 1
stack2 = [3, 2, 1] #真正的pop/top操作在stack2上執行

完整代碼

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack1 = []
        self.stack2 = []
        

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.stack1.append(x)
        

    def pop(self):
        """
        :rtype: nothing
        """
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()
        

    def peek(self):
        """
        :rtype: int
        """
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]
        

    def empty(self):
        """
        :rtype: bool
        """
        return len(self.stack1) == 0 and len(self.stack2) == 0
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容