學習如何在Python中實現(xiàn)單向鏈表。探索使用Python代碼示例的數(shù)據(jù)結構和算法分析基礎知識。
Python 實現(xiàn)單向鏈表詳細教程
在計算機科學中,單向鏈表是一種基本的數(shù)據(jù)結構,用于存儲元素集合。每個節(jié)點包含一個數(shù)據(jù)元素和指向下一個節(jié)點的引用(鏈接)。讓我們深入了解如何使用Python實現(xiàn)單向鏈表。文章來源:http://www.zghlxwxcb.cn/article/722.html
示例代碼
class Node: def __init__(self, elem): """ 初始化具有元素值和下一個節(jié)點引用的節(jié)點。 :param elem: 節(jié)點的元素值 """ self.elem = elem self.next = None class SingleLinkList: """ 單向鏈表由節(jié)點組成,每個節(jié)點包含一個元素和指向下一個節(jié)點的鏈接。 """ def __init__(self, node=None): self.__head = node def is_empty(self): """ 檢查鏈表是否為空 """ return self.__head is None def length(self): """ 返回鏈表的長度 """ cur = self.__head count = 0 while cur is not None: count += 1 cur = cur.next return count def travel(self): """ 遍歷鏈表 """ cur = self.__head while cur is not None: print(cur.elem, end=' ') cur = cur.next def add(self, item): """ 在鏈表開頭添加元素(頭部插入) """ node = Node(item) node.next = self.__head self.__head = node def append(self, item): """ 在鏈表末尾添加元素(尾部插入) """ node = Node(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next is not None: cur = cur.next cur.next = node def insert(self, pos, item): """ 在特定位置插入元素 """ if pos <= 0: self.add(item) elif pos > (self.length() - 1): self.append(item) else: pre = self.__head count = 0 while count < (pos - 1): count += 1 pre = pre.next node = Node(item) node.next = pre.next pre.next = node def remove(self, item): """ 從鏈表中刪除元素 """ cur = self.__head pre = None while cur is not None: if cur.elem == item: if cur == self.__head: self.__head = cur.next else: pre.next = cur.next break else: pre = cur cur = cur.next def search(self, item): """ 查找具有特定元素的節(jié)點 """ cur = self.__head while cur is not None: if cur.elem == item: return True else: cur = cur.next return False if __name__ == '__main__': ll = SingleLinkList() ll.is_empty() ll.append(55) ll.is_empty() ll.append(2) ll.add(8) ll.append(3) ll.append(4) ll.append(5) ll.insert(-1, 9) ll.insert(2, 100) ll.travel()
文章來源地址http://www.zghlxwxcb.cn/article/722.html
到此這篇關于Python數(shù)據(jù)結構與算法分析:實現(xiàn)單向鏈表的文章就介紹到這了,更多相關內容可以在右上角搜索或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!