Python棧的實現方法

2022-05-10 01:27:55 字數 697 閱讀 5864

class

stack:

def__init__

(self):

#例項乙個空列表物件

self.items =

defisempty(self):

#判斷列表中是否有值,空就返回true

return self.items ==

defpush(self, item):

#從列表末尾新增資料

defpop(self):

#列表方法pop會返回乙個末尾已刪除的值

return

self.items.pop()

defpeek(self):

#獲取列表資料多少並取得最後乙個

return self.items[len(self.items) - 1]

defsize(self):

#返回列表資料的多少

return

len(self.items)

s = stack() #

例項化乙個棧

print(s.isempty()) #

還沒新增資料為true

print(s.push(1)) #

沒有返回值none

print(s.pop()) #

返回已刪除資料

view code

python出棧的方法 Python實現棧的方法

定義乙個列表來模擬棧 stack def pu 出棧,用到了pop 函式 def popit if len stack 0 print cannot pop from an empty stack else print removed stack.pop 編歷棧 def viewstack prin...

python出棧的方法 Python實現棧的方法

usr bin env python 定義乙個列表來模擬棧 stack def pu 出棧,用到了pop 函式 def popit if len stack 0 print cannot pop from an empty stack else print removed stack.pop 編歷棧...

用python實現棧 Python實現棧的方法

usr bin env python 定義乙個列表來模擬棧 stack def pu 出棧,用到了pop 函式 def popit if len stack 0 print cannot pop from an empty stack else print removed stack.pop 編歷棧...