新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
python如何表示鏈表
鏈表是一種線性數(shù)據(jù)結(jié)構(gòu),其中的元素通過指針鏈接在一起,在Python中,我們可以使用類來表示鏈表,以下是一個簡單的鏈表實現(xiàn):

成都創(chuàng)新互聯(lián)是一家專業(yè)提供巴南企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站設(shè)計、成都網(wǎng)站建設(shè)、H5場景定制、小程序制作等業(yè)務(wù)。10年已為巴南眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進行中。
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
new_node = ListNode(value)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def display(self):
current = self.head
while current:
print(current.value, end=" > ")
current = current.next
print("None")
在這個實現(xiàn)中,我們定義了兩個類:ListNode 和 LinkedList。ListNode 類表示鏈表中的每個元素,它包含一個值(value)和一個指向下一個元素的指針(next)。LinkedList 類表示整個鏈表,它包含一個指向鏈表頭部的指針(head)。
LinkedList 類有兩個方法:append 和 display。append 方法用于在鏈表末尾添加一個新元素,display 方法用于打印鏈表中的所有元素。
以下是如何使用這個鏈表實現(xiàn)的示例:
創(chuàng)建一個空鏈表 linked_list = LinkedList() 向鏈表中添加元素 linked_list.append(1) linked_list.append(2) linked_list.append(3) 顯示鏈表中的元素 linked_list.display() # 輸出:1 > 2 > 3 > None
當(dāng)前標(biāo)題:python如何表示鏈表
網(wǎng)站地址:http://www.5511xx.com/article/djhejjp.html


咨詢
建站咨詢
