a、鍊錶的結構為:
b、鍊錶的實現方法;
#鍊錶結構實現 私有屬性_pro_item是指向下個節點的指標,_item為此節點的值
class
chaindemo():
def__init__(self,item = none,pos_item=none):
self._item =item
self._pos_item =pos_item
if__name__ == '
__main__':
chain = chaindemo('
a',(chaindemo('
b',chaindemo('
c',chaindemo('d'
)))))
while
true:
(chain._item)
if chain._pos_item !=none:
chain =chain._pos_item
else
:
break
#鍊錶節點結構實現 私有屬性_pro_item是指向下個節點的指標,_item為此節點的值
class
node():
def__init__(self,item = none,pos_item=none):
self._item =item
self._next =pos_item
def__repr__
(self):
'''用來定義node的字元輸出,
print為輸出item
'''return
str(self._item)
#單鏈表實現
class
chain():
def__init__
(self):
self._head =none
self.length =0
#判空defisempty(self):
return self.length ==0
#鍊錶結尾插入
def
ifisinstance(item,node):
node =item
else
: node =node(item)
if self._head ==none:
self._head =node
else
: be_node =self._head
while
be_node._next:
be_node =be_node._next
be_node._next =node
self.length += 1
#插入資料
definsert(self,index,item):
ifself.isempty():
print('
this chain table is empty')
return
if index<0 or index >=self.length:
print("
error: out of index")
return
in_node =node(item)
node =self._head
count = 1
while
true:
node =node._next
count += 1
if count ==index:
next_node =node._next
node._next =in_node
in_node._next =next_node
self.length += 1
return
#node = s
#刪除資料
defdelete(self,index):
ifself.isempty():
print('
this chain table is empty')
return
if index<0 or index >=self.length:
print("
error: out of index")
return
#if index == 0
#self._head = none
else
: node =self._head
count =0
while
true:
count += 1
if index ==count:
node._next =node._next._next
break
node =node._next
self.length -= 1
def__repr__
(self):
ifself.isempty():
print("
the chain table is empty")
return
nlist = ""
node =self._head
while
node:
nlist += node._item +''
node =node._next
return
nlist
if__name__ == '
__main__':
chain =chain()'a
')'b
')'c
')'d
')'e
')'f
')'g
')chain.insert(4,'p'
) chain.delete(3)
print(chain,chain._head._item,chain.length)
python3實現單向鍊錶
python3實現單向鍊錶 最近重學資料結構,無奈c語言已經忘得一乾二淨,所以乾脆用python來寫。一 結構 節點類 單向列表類 鍊錶初始化操作 init 初始化鍊錶 is empty 判斷鍊錶是否為空 get len 獲取鍊錶的長度 clear list 清除列表 增加節點 insert 在鍊錶...
leetcode 回文鍊錶 python3
class solution def ispalindrome self,head 判斷乙個鍊錶是否是回文的,很自然的想法就是兩個指標,乙個指標從前往後走,乙個指標從後往前走,判斷元素值是否相同,這裡要分幾個步驟來進行求解 1 找到鍊錶長度的一半,用追趕法,乙個指標一次走兩步,乙個指標一次走一步 2...
Python3 雙向鍊錶
雙向鍊錶 每乙個元素都是乙個物件,每個物件有乙個關鍵字key和兩個指標 next和prev 在雙向鍊錶的實現中,使用乙個偽頭部 dummy head 和偽尾部 dummy tail 標記界限,這樣在新增節點和刪除節點的時候就不需要檢查相鄰的節點是否存在。class dlinkednode def i...