顶点表 + 边表 // 前者是数组,后者是单链表
#include <iostream> #include <cstdio> #include <cstdlib> using namespace std; const int VERTEX_NUM = 20; // 最大允许的顶点数 // 边表的结点(单链表) class EdgeNode { public: int vertexData; int weight; EdgeNode *next; }; // 顶点表的结点 class VertexNode { public: int vertexData; EdgeNode *firstEdge; }; // 图的结构 class Graph { public: VertexNode vertex[VERTEX_NUM]; int vertexNum; // 当前图的顶点数 int edgeNum; // 当前图的边数 }; void createGraph(Graph &G) { cout << "请输入无向图的顶点数和边数:"; cin >> G.vertexNum >> G.edgeNum; // 读入顶点信息,建立顶点表 for (int i = 0; i != G.vertexNum; ++i) { cout << "请输入第" << i + 1 << "个顶点的序号:"; cin >> G.vertex[i].vertexData; G.vertex[i].firstEdge = NULL; // 将边表置位空表 } // 建立边表 for (int k = 0; k != G.edgeNum; ++k) { cout << "请输入边(vi, vj)的顶点i、j及权重w:"; int i, j, w; cin >> i >> j >> w; EdgeNode *q = (EdgeNode*)malloc(sizeof(EdgeNode)); // 生成边表结点,下同单链表的头插入 q->vertexData = j; q->weight = w; q->next = G.vertex[i].firstEdge; G.vertex[i].firstEdge = q; // 无向图要再设置另一半 EdgeNode *s = (EdgeNode*)malloc(sizeof(EdgeNode)); // 生成边表结点 s->vertexData = i; s->weight = w; s->next = G.vertex[j].firstEdge; G.vertex[j].firstEdge = s; } } int main() { Graph G; createGraph(G); }