單鏈表實現棧操作,規定棧頂在鍊錶的頭部
**如下:
# -*- coding:utf-8 -*-
class
linkedstack
:class
node
:def
__init__
(self,element,
next):
self.element = element
self.
next
=next
#棧方法
def__init__
(self)
: self.head =
none
self.size =
0def
_len_
(self)
:return self.size
defis_empty
(self)
:return self.size ==
0def
push
(self, e)
: self.head = self.node(e,self.head)
#上一條語句喝下面3條語句等價,下面3條語句好理解
# ~ p = self.node(e,self.head)
# ~ p.next = self.head
# ~ self.head = p
self.size +=
1def
top(self)
:if self.is_empty():
print
('stack is empty'
)return self.head.element
defpop(self)
:if self.is_empty():
print
('stack is empty'
) answer = self.head.element
self.head = self.head.
next
self.size -=
1return answer
if __name__==
'__main__'
: s = linkedstack(
) s.push(1)
s.push(2)
s.push(
3)
s.push(4)
s.push(5)
s.pop(
) s.pop(
) s.push(24)
print
(s.head.element)
print
(s.head.
next
.element)
print
(s.head.
next
.next
.element)
print
(s.head.
next
.next
.next
.element)
測試結果如下:
python用單鏈表實現棧
class lnode 節點的類 def init self,x self.data x self.next none class mystack 用鍊錶實現棧 def init self self.data none self.next none 判斷棧是否為空 def isempty self ...
單鏈表實現棧
程式設計實現下面的棧頂操作 cpp view plain copy print?class mydata 解析 顯然這裡需要實現棧的3種基本操作,即進棧 出棧以及判空。為了方便起見,使用單鏈表結構實現棧並且使用類的形式來定義站內及其節點。首先是節點類和棧類的具體定義,程式 如下 cpp view p...
python實現單鏈表
code python code coding utf 8 class node def init self,value self.data value self.next none class linklist def init self,data 0 self.head none self.in...