在学习数据结构的过程中,图(Graph)是一种非常重要的非线性结构。图的存储方式有多种,其中邻接多重表(Adjacency Multilist)是专门用于无向图的一种高效存储结构。本教程将带你从零开始,使用Python语言一步步实现邻接多重表。
邻接多重表是邻接表的改进版本,特别适用于无向图。在邻接表中,每条边会被存储两次(因为无向图的边是双向的),而邻接多重表通过让两个顶点共享同一条边结点,节省了存储空间,并方便对边进行操作(如标记是否访问过)。

我们需要定义两种节点:
下面我们将用Python类来实现邻接多重表。为了便于理解,我们不使用复杂的指针,而是用列表和对象引用来模拟。
class EdgeNode: def __init__(self, ivex, jvex, weight=1): self.ivex = ivex # 顶点i的索引 self.jvex = jvex # 顶点j的索引 self.weight = weight # 边的权重(可选) self.marked = False # 是否被访问过 self.ilink = None # 指向顶点i的下一条边 self.jlink = None # 指向顶点j的下一条边class VertexNode: def __init__(self, data): self.data = data # 顶点数据(如名称) self.first_edge = None # 指向第一条关联边class AdjacencyMultilist: def __init__(self): self.vertices = [] # 顶点列表 def add_vertex(self, data): """添加顶点""" self.vertices.append(VertexNode(data)) def add_edge(self, i, j, weight=1): """添加无向边 (i, j)""" if i >= len(self.vertices) or j >= len(self.vertices): raise IndexError("顶点索引超出范围") edge = EdgeNode(i, j, weight) # 将新边插入到顶点i的边链表头部 edge.ilink = self.vertices[i].first_edge self.vertices[i].first_edge = edge # 将新边插入到顶点j的边链表头部 edge.jlink = self.vertices[j].first_edge self.vertices[j].first_edge = edge def display(self): """打印邻接多重表结构""" for idx, vertex in enumerate(self.vertices): print(f"顶点 {vertex.data} 的边:") edge = vertex.first_edge while edge: other = edge.jvex if edge.ivex == idx else edge.ivex print(f" -> 连接到 {self.vertices[other].data}, 权重={edge.weight}") # 根据当前顶点选择正确的link edge = edge.ilink if edge.ivex == idx else edge.jlink现在我们创建一个简单的无向图并测试我们的实现:
# 创建图graph = AdjacencyMultilist()# 添加4个顶点for v in ['A', 'B', 'C', 'D']: graph.add_vertex(v)# 添加边graph.add_edge(0, 1) # A-Bgraph.add_edge(0, 2) # A-Cgraph.add_edge(1, 2) # B-Cgraph.add_edge(2, 3) # C-D# 显示图结构graph.display()运行结果将显示每个顶点连接的所有边,清晰地反映出图的结构。
相比邻接矩阵和邻接表,邻接多重表在处理无向图时具有以下优势:
通过本教程,你已经学会了如何用Python语言实现邻接多重表这一重要的图的存储结构。无论你是初学者还是有一定基础的学习者,掌握这种结构都将帮助你在解决图论问题时更加得心应手。希望这篇数据结构教程对你有所帮助!
关键词回顾:Python邻接多重表、图的存储结构、邻接多重表实现、数据结构教程。
本文由主机测评网于2025-12-13发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025127070.html