python堆疊實現

2022-09-20 06:03:08 字數 1505 閱讀 8055

#-*- coding:utf-8 -*-

__metaclass__ = type

class

mystack

():def

__init__

(self,value):

self.value = value

self.behind = none

self.before = none

def__str__

(self):

return str(self.value)

deftop

(stack):

#頂部if isinstance(stack,mystack):

if stack.behind is

notnone:

return top(stack.behind)

else:

return stack

else:

print ('沒有初始化')

defpush

(stack,elem):

#入棧 in_elem = mystack(elem)

if isinstance(stack,mystack):

now_top = top(stack)

in_elem.before = now_top

in_elem.before.behind = in_elem

print ('成功入棧')

else:

print ('沒有初始化')

defpop

(stack):

#出棧if isinstance(stack,mystack):

now_top = top(stack)

if now_top.before is

notnone:

now_top.before.behind = none

now_top.before = none

return now_top

else:

return('棧空了')

else:

return('沒有初始化')

demo1 = mystack(1) #初始化,只能通過demo1訪問

for i in range(10): #入棧

push(demo1,i)

print

'---------------'

print demo1

for p in range(11): #出棧

print pop(demo1)

輸出:成功入棧

成功入棧

成功入棧

成功入棧

成功入棧

成功入棧

成功入棧

成功入棧

成功入棧

成功入棧

---------------19

8765

4321

0棧空了

[finished in

0.5s]

python實現堆疊 佇列

一 利用python列表實現堆疊和佇列 堆疊 堆疊是乙個後進先出的資料結構,其工作方式就像生活中常見到的直梯,先進去的人肯定是最後出。後進先出 class stack def init self,size self.size size self.stack self.top 1 defpush se...

用python實現佇列,堆疊

stack 堆疊 後進先出 queue佇列 先進先出 fifo first in first out putget queue佇列 先進先出 fifo first in first out put get class queue def init self self.l def put self,i...

python實現堆疊與佇列的方法

1 python實現堆疊,可先將stack類寫入檔案stack.py,在其它程式檔案中使用frwww.cppcns.comom stack import stack,然後就可以使用堆疊了。stack.py的程式 複製 如下 class stack def init self,size self.si...