class list_node: def __init__(self): self.val = 0 self.next = None #建立鏈表類 head = [list_node()] * 6 # 聲明一個節點類型的鏈表 newnode = list_node() # 圖的數組聲明 data = [[1, 2], [2, 1], [2, 5], [5, 2], \ [2, 3], [3, 2], [2, 4], [4, 2], \ [3, 4], [4, 3], [3, 5], [5, 3], \ [4, 5], [5, 4]] print('圖的鄰接表內容:') print('----------------------------------') for i in range(1, 6): head[i].val = i # 鏈表頭head head[i].next = None print('頂點 %d =>' % i, end='') # 把頂點值打印出來 ptr = head[i] for j in range(14): # 遍歷圖的數組 if data[j][0] == i: # 若是節點值=i,加入節點到鏈表頭 #print('######', newnode.val) newnode.val = data[j][1] # 聲明新節點,值爲終點值 newnode.next = None while ptr != None: # 判斷是否爲鏈表的末尾 ptr = ptr.next ptr = newnode # 加入新節點 print('[%d] ' % newnode.val, end='') # 打印相鄰頂點 print()