
力扣在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()