用 python 的 list 實現棧

2021-08-29 05:31:52 字數 1056 閱讀 9095

介紹一下:

棧作為一種資料結構,是一種只能在一端進行插入和刪除操作的特殊線性表。

用 python 的順序表 list 實現:

#coding=utf-8

__date__ =

' 21:50'

__author__ =

'sixkery'

class

stact

(object):

'''棧'''

# 構造乙個棧的容器

def__init__

(self)

: self.__list =

defpush

(self,item)

:'''新增乙個新的元素到棧頂'''

defpop

(self)

:'''彈出棧頂元素'''

return self.__list.pop(

)def

peek

(self)

:'''返回棧頂元素'''

if self.__list:

return self.__list[-1

]return

none

defis_empty

(self)

:'''判斷棧是否為空'''

return self.__list ==

defsize

(self)

:'''返回棧的的元素個數'''

return

len(self.__list)

if __name__ ==

'__main__'

: s = stact(

) s.push(1)

s.push(2)

s.push(3)

s.push(4)

print

(s.pop())

print

(s.pop())

print

(s.pop())

print

(s.pop(

))

Python用List實現棧和佇列

class stack def init self self.items 初始化乙個列表 defis empty self 如果為空則返回true 否則返回false return self.items defpop self try return self.items.pop except rai...

用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內建的list實現 class stack object def init self self.stack defpush self,item def peek self if self.isemp...