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

創(chuàng)新互聯(lián)建站自2013年起,先為桐城等服務(wù)建站,桐城等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為桐城企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
1、定義節(jié)點(diǎn)類(Node):
class Node:
def __init__(self, data):
self.data = data
self.next = None
2、定義鏈表類(LinkedList):
class LinkedList:
def __init__(self):
self.head = None
# 添加元素到鏈表末尾
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
# 打印鏈表元素
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data, end=" > ")
cur_node = cur_node.next
print("None")
3、使用鏈表類:
創(chuàng)建一個(gè)鏈表對象 linked_list = LinkedList() 向鏈表中添加元素 linked_list.append(1) linked_list.append(2) linked_list.append(3) 打印鏈表元素 linked_list.print_list()
輸出結(jié)果:
1 > 2 > 3 > None
標(biāo)題名稱:python如何實(shí)現(xiàn)鏈表
分享路徑:http://m.fisionsoft.com.cn/article/djpcjio.html


咨詢
建站咨詢
