# 数据结构（八）：邻接表与邻接矩阵

+关注继续查看

graph

digraph

### 代码附录

##### 邻接表结构
# graph node definition
class Node(object):
def __init__(self, index, weight, next = None):
self.index = index
self.weight = weight
self.next = next

def __init__(self, number):
self.number = number
self.list = [None] * number

# insert node
def insert(self, origin, index, weight = 1):
node = Node(index, weight, self.list[origin - 1])
self.list[origin - 1] = node


if __name__ == '__main__':
graph.insert(1, 2)
graph.insert(1, 3)
graph.insert(1, 4)
graph.insert(2, 3)
graph.insert(3, 1)
graph.insert(3, 5)
graph.insert(4, 3)
for i in range(graph.number):
print('node', (i + 1), 'links:', end = ' ')
node = graph.list[i]
while node:
print(node.index, end = ' ')
node = node.next
print()


node 1 links: 4 3 2

##### 邻接矩阵结构
# adjacency list definition
def __init__(self, number):
self.number = number
self.list = [[None] * number for i in range(number)]

# insert node
def insert(self, origin, index, weight = 1):
self.list[origin - 1][index - 1] = weight


if __name__ == '__main__':
graph.insert(1, 2)
graph.insert(1, 3)
graph.insert(1, 4)
graph.insert(2, 3)
graph.insert(3, 1)
graph.insert(3, 5)
graph.insert(4, 3)
for i in range(graph.number):
print('node', (i + 1), 'links:', end = ' ')
j = 0
while j < graph.number:
print(j + 1, end = ' ') if graph.list[i][j] else None
j += 1
print()


node 1 links: 2 3 4


github 链接：邻接表与邻接矩阵

|
2月前
|

33 0
|
5月前
|

【数据结构】图邻接矩阵的创建完整代码
【数据结构】图邻接矩阵的创建完整代码
127 0
|
6月前
|

166 0
|
10月前

38 0
|
10月前

30 0
|

1437 0
|

【数据结构】图的存储结构—邻接矩阵
【数据结构】图的存储结构—邻接矩阵
519 0
|

84 0
|

1748 0
|

1211 0