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)都包含了可以鏈接起來的地址信息,所以用一個(gè)變量就能夠訪問整個(gè)結(jié)點(diǎn)序列。也就是說,結(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)沒有后繼元素,其指針域?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): ’列表長度’ 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. ASP基礎(chǔ)知識(shí)VBScript基本元素講解2. jsp中sitemesh修改tagRule技術(shù)分享3. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除4. React優(yōu)雅的封裝SvgIcon組件示例5. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)6. JavaWeb Servlet中url-pattern的使用7. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究8. 輕松學(xué)習(xí)XML教程9. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼10. 詳解瀏覽器的緩存機(jī)制
