Leetcode 每日一題 python解法 3月1日


力扣在3月1日到4月30日推出了每日一題活動,我來試試看吧


image.png

難度:簡單

題目內(nèi)容:

使用隊列實現(xiàn)棧的下列操作:

push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否為空
注意:

你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。
你所使用的語言也許不支持隊列。 你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
你可以假設所有操作都是有效的(例如, 對一個空的棧不會調(diào)用 pop 或者 top 操作)。

題解

還是蠻簡單的,先來確認一下什么是棧
棧是一種只能在一端進行插入和刪除操作的特殊線性表。它按照先進后出的原則存儲數(shù)據(jù),先進入的數(shù)據(jù)被壓入棧底,最后的數(shù)據(jù)在棧頂,需要讀數(shù)據(jù)的時候從棧頂開始彈出數(shù)據(jù)(最后一個數(shù)據(jù)被第一個讀出來)。
可以使用list或者queue來實現(xiàn)。

list實現(xiàn)

push(x)---->list.append()
pop()---->list.pop()
top() ----> 返回list[-1]
empty() ---->返回list == []

解答:

class MyStack:

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


    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.queue.append(x)




    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.queue.pop()

    def top(self) -> int:
        """
        Get the top element.
        """
        return self.queue[-1]


    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return self.queue == []

使用LifoQueue

import queue
class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue = queue.LifoQueue(maxsize=0)


    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.queue.put(x)




    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.queue.get()

    def top(self) -> int:
        """
        Get the top element.
        """
        res = self.queue.get()
        self.queue.put(res)
        return res

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return self.queue.empty()
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容