思路
鍊錶由節點組成,先規定節點(node),包含data和指向下個節點的next
初始化data當然就是傳入的data了,next指向none
新增分兩種情況:
鍊錶為空,那麼頭節點和尾節點都指向新插入的節點
鍊錶不為空,那麼直接在尾部新增即可
遍歷因為只有鍊錶的尾節點的next是指向none的,所以可以根據這點來從頭遍歷
刪除某個節點
刪除的時候分3種情況:
頭節點,此時更改head指向的節點就好了
尾節點,此時只需將尾節點的前乙個節點(prev)的next指向none即可
中間的節點,此時要將此節點的前乙個節點的(prev)的next指向後續節點的(current.next)
搜尋遍歷查詢即可
清空鍊錶
將頭節點和尾節點都置為none即可
class node:
def __init__(self,data):
self.next = none
self.data = data
class singlylinkedlist:
def __init__(self):
self.head = none #頭節點
self.tail = none #尾節點
self.size = 0 #鍊錶長度
node = node(data)
if self.tail: #如果鍊錶不為空
self.tail.next = node
self.tail = node
else:
self.head = node
self.tail = node #如果這是第乙個插入的節點那麼頭和尾都指向此節點
self.size += 1
def iter(self):
'''遍歷鍊錶'''
current = self.head
while current:
value = current.data
current = current.next
yield value
def delete(self,data):
'''根據資料刪除節點'''
current = self.head
prev = self.head
while current:
if current.data == data:
if current == self.head:
self.head = current.next
elif current == self.tail:
prev.next = none
self.tail = prev
else:
prev.next = current.next
self.size -= 1
return
prev = current
current = current.next
def search(self,data):
'''搜尋某個節點'''
for node in self.iter():
if data == node:
return true
return false
def clear(self):
'''清空鍊錶'''
self.tail = none
self.head = none
Python 實現單向鍊錶
鍊錶顧名思義就是 鏈 鍊錶是一種動態資料結構,他的特點是用一組任意的儲存單元存放資料元素。鍊錶中每乙個元素成為 結點 每乙個結點都是由資料域和指標域組成的。跟陣列不同鍊錶不用預先定義大小,而且硬體支援的話可以無限擴充套件。陣列需要預先定義大小,無法適應資料動態地增減,資料小於定義的長度會浪費記憶體,...
Python 實現單向動態鍊錶
鍊錶顧名思義就是 鏈 鍊錶是一種動態資料結構,他的特點是用一組任意的儲存單元存放資料元素。鍊錶中每乙個元素成為 結點 每乙個結點都是由資料域和指標域組成的。跟陣列不同鍊錶不用預先定義大小,而且硬體支援的話可以無限擴充套件。陣列需要預先定義大小,無法適應資料動態地增減,資料小於定義的長度會浪費記憶體,...
實現單向鍊錶
鍊錶類 public class link 增加節點 public void add node node else 輸出節點 public void print else 內部搜尋節點的方法 public boolean search string data 直到不存在下乙個節點結束搜尋 if th...