python如何對(duì)鏈表操作
鏈表
鏈表(linked list)是由一組被稱為結(jié)點(diǎn)的數(shù)據(jù)元素組成的數(shù)據(jù)結(jié)構(gòu),每個(gè)結(jié)點(diǎn)都包含結(jié)點(diǎn)本身的信息和指向下一個(gè)結(jié)點(diǎn)的地址。由于每個(gè)結(jié)點(diǎn)都包含了可以鏈接起來(lái)的地址信息,所以用一個(gè)變量就能夠訪問(wèn)整個(gè)結(jié)點(diǎn)序列。也就是說(shuō),結(jié)點(diǎn)包含兩部分信息:一部分用于存儲(chǔ)數(shù)據(jù)元素的值,稱為信息域;另一部分用于存儲(chǔ)下一個(gè)數(shù)據(jù)元素地址的指針,稱為指針域。鏈表中的第一個(gè)結(jié)點(diǎn)的地址存儲(chǔ)在一個(gè)單獨(dú)的結(jié)點(diǎn)中,稱為頭結(jié)點(diǎn)或首結(jié)點(diǎn)。鏈表中的最后一個(gè)結(jié)點(diǎn)沒(méi)有后繼元素,其指針域?yàn)榭铡?/p>
代碼
class Node(): ’創(chuàng)建節(jié)點(diǎn)’ def __init__(self, data): self.data = data self.next = Noneclass LinkList(): ’創(chuàng)建列表’ def __init__(self, node): ’初始化列表’ self.head = node #鏈表的頭部 self.head.next = None self.tail = self.head #記錄鏈表的尾部 def add_node(self, node): ’添加節(jié)點(diǎn)’ 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): ’列表長(zhǎng)度’ 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é)點(diǎn)’ 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é)點(diǎn)’ 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.datanode1 = 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如何對(duì)鏈表操作的詳細(xì)內(nèi)容,更多關(guān)于python 鏈表操作的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. el-input無(wú)法輸入的問(wèn)題和表單驗(yàn)證失敗問(wèn)題解決2. 父div高度不能自適應(yīng)子div高度的解決方案3. ASP動(dòng)態(tài)include文件4. 不要在HTML中濫用div5. Vue中原生template標(biāo)簽失效如何解決6. XML入門的常見(jiàn)問(wèn)題(三)7. XML 非法字符(轉(zhuǎn)義字符)8. vue跳轉(zhuǎn)頁(yè)面常用的幾種方法匯總9. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)10. js開(kāi)發(fā)中的頁(yè)面、屏幕、瀏覽器的位置原理(高度寬度)說(shuō)明講解(附圖)
