Python數(shù)據(jù)結(jié)構(gòu)鏈表操作從基礎(chǔ)到高級實(shí)例深究
實(shí)現(xiàn)單向鏈表
讓我們首先看一個簡單的單向鏈表的實(shí)現(xiàn):
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node return last_node = self.head while last_node.next: last_node = last_node.next last_node.next = new_node def display(self): current = self.head while current: print(current.data, end=' -> ') current = current.next print('None')
創(chuàng)建鏈表并展示
# 創(chuàng)建鏈表 my_list = LinkedList() my_list.append(1) my_list.append(2) my_list.append(3) # 展示鏈表 my_list.display()
鏈表操作:插入和刪除節(jié)點(diǎn)
class LinkedList: # ...(上面的代碼) def insert_after(self, prev_node, data): if not prev_node: print("Previous node is not in the list.") return new_node = Node(data) new_node.next = prev_node.next prev_node.next = new_node def delete_node(self, key): current = self.head if current and current.data == key: self.head = current.next current = None return prev = None while current and current.data != key: prev = current current = current.next if current is None: return prev.next = current.next current = None
演示插入和刪除操作
# 創(chuàng)建鏈表 my_list = LinkedList() my_list.append(1) my_list.append(3) my_list.append(4) # 插入節(jié)點(diǎn) node = my_list.head.next my_list.insert_after(node, 2) # 刪除節(jié)點(diǎn) my_list.delete_node(3) # 展示鏈表 my_list.display()
總結(jié)
鏈表是一種基本而靈活的數(shù)據(jù)結(jié)構(gòu),在Python中通過類的構(gòu)建可以輕松實(shí)現(xiàn)。本文通過詳細(xì)的示例代碼演示了單向鏈表的創(chuàng)建、節(jié)點(diǎn)插入、刪除等基本操作。通過Node節(jié)點(diǎn)和LinkedList類的概念,我們了解了鏈表是由節(jié)點(diǎn)組成的,每個節(jié)點(diǎn)包含數(shù)據(jù)和指向下一個節(jié)點(diǎn)的引用。
鏈表在插入和刪除操作上表現(xiàn)出高效性,使其成為處理大量數(shù)據(jù)變動的理想選擇。通過這些示例,讀者能夠更深入地了解鏈表的內(nèi)部工作原理以及如何應(yīng)用它來解決實(shí)際問題??偟膩碚f,本文提供了一個全面的入門級指南,旨在理解鏈表的核心概念并為在日常編程中更好地利用這一數(shù)據(jù)結(jié)構(gòu)奠定基礎(chǔ)。
以上就是Python基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)鏈表的實(shí)現(xiàn)從基礎(chǔ)到高級實(shí)例深究的詳細(xì)內(nèi)容,更多關(guān)于Python數(shù)據(jù)結(jié)構(gòu)鏈表的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python解析發(fā)往本機(jī)的數(shù)據(jù)包示例 (解析數(shù)據(jù)包)
這篇文章主要介紹了使用python解析獲取發(fā)往本機(jī)的數(shù)據(jù)包,并打印出來, 大家參考使用吧2014-01-01Python實(shí)現(xiàn)PS濾鏡的旋轉(zhuǎn)模糊功能示例
這篇文章主要介紹了Python實(shí)現(xiàn)PS濾鏡的旋轉(zhuǎn)模糊功能,涉及Python基于skimage庫針對圖片進(jìn)行旋轉(zhuǎn)與模糊化處理的相關(guān)操作技巧,需要的朋友可以參考下2018-01-01Python如何生成指定區(qū)間中的隨機(jī)數(shù)
這篇文章主要介紹了Python如何生成指定區(qū)間中的隨機(jī)數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07