python如何對鏈表操作
鏈表
鏈表(linked list)是由一組被稱為結(jié)點的數(shù)據(jù)元素組成的數(shù)據(jù)結(jié)構(gòu),每個結(jié)點都包含結(jié)點本身的信息和指向下一個結(jié)點的地址。
由于每個結(jié)點都包含了可以鏈接起來的地址信息,所以用一個變量就能夠訪問整個結(jié)點序列。
也就是說,結(jié)點包含兩部分信息:一部分用于存儲數(shù)據(jù)元素的值,稱為信息域;另一部分用于存儲下一個數(shù)據(jù)元素地址的指針,稱為指針域。鏈表中的第一個結(jié)點的地址存儲在一個單獨的結(jié)點中,稱為頭結(jié)點或首結(jié)點。鏈表中的最后一個結(jié)點沒有后繼元素,其指針域為空。
代碼
class Node(): '創(chuàng)建節(jié)點' def __init__(self, data): self.data = data self.next = None class LinkList(): '創(chuàng)建列表' def __init__(self, node): '初始化列表' self.head = node #鏈表的頭部 self.head.next = None self.tail = self.head #記錄鏈表的尾部 def add_node(self, node): '添加節(jié)點' self.tail.next = node self.tail = self.tail.next def view(self): '查看列表' node = self.head link_str = '' while node is not None: if node.next is not None: link_str += str(node.data) + '-->' else: link_str += str(node.data) node = node.next print('The Linklist is:' + link_str) def length(self): '列表長度' node = self.head count = 1 while node.next is not None: count += 1 node = node.next print('The length of linklist are %d' % count) return count def delete_node(self, index): '刪除節(jié)點' if index + 1 > self.length(): raise IndexError('index out of bounds') num = 0 node = self.head while True: if num == index - 1: break node = node.next num += 1 tmp_node = node.next node.next = node.next.next return tmp_node.data def find_node(self, index): '查看具體節(jié)點' if index + 1 > self.length(): raise IndexError('index out of bounds') num = 0 node = self.head while True: if num == index: break node = node.next num += 1 return node.data node1 = Node(3301) node2 = Node(330104) node3 = Node(330104005) node4 = Node(330104005052) node5 = Node(330104005052001) linklist = LinkList(node1) linklist.add_node(node2) linklist.add_node(node3) linklist.add_node(node4) linklist.add_node(node5) linklist.view() linklist.length()
以上就是python如何對鏈表操作的詳細(xì)內(nèi)容,更多關(guān)于python 鏈表操作的資料請關(guān)注腳本之家其它相關(guān)文章!
- python實現(xiàn)數(shù)據(jù)結(jié)構(gòu)中雙向循環(huán)鏈表操作的示例
- python操作鏈表的示例代碼
- python/golang 刪除鏈表中的元素
- python/golang實現(xiàn)循環(huán)鏈表的示例代碼
- python的鏈表基礎(chǔ)知識點
- 用python介紹4種常用的單鏈表翻轉(zhuǎn)的方法小結(jié)
- Python實現(xiàn)鏈表反轉(zhuǎn)的方法分析【迭代法與遞歸法】
- Python實現(xiàn)隊列的方法示例小結(jié)【數(shù)組,鏈表】
- python實現(xiàn)從尾到頭打印單鏈表操作示例
- Python棧的實現(xiàn)方法示例【列表、單鏈表】
- Python單鏈表原理與實現(xiàn)方法詳解
- python判斷鏈表是否有環(huán)的實例代碼
相關(guān)文章
Python設(shè)計模式編程中解釋器模式的簡單程序示例分享
這篇文章主要介紹了Python設(shè)計模式編程中解釋器模式的簡單程序示例分享,解釋器模式強(qiáng)調(diào)用抽象類來表達(dá)程序中將要實現(xiàn)的功能,需要的朋友可以參考下2016-03-03python內(nèi)置函數(shù)frozenset()的使用小結(jié)
本篇文章主要介紹了python內(nèi)置函數(shù)frozenset()的使用小結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05