1、邻接矩阵
#include <iostream> using namespace std; #define MaxSize 100 typedef char VertexType[3]; typedef struct Vertex{ int adjvex; //顶点编号 VertexType data; //顶点的信息 }VType; typedef struct graph{ int n,e; //实际点数和边数 VType vexs[MaxSize]; //顶点集合 int edges[MaxSize][MaxSize]; //边集合 }Graph; void Create(Graph& g){ int b,e,w; cout << "顶点数n和边数e:"; cin >> g.n >> g.e; cout << endl << "输入顶点信息:"; for(size_t i=0;i<g.n;i++){ cin >> g.vexs[i].data; g.vexs[i].adjvex = i; } for(size_t i=0;i<g.n;i++){ for(size_t j=0;j<g.n;j++){ g.edges[i][j] = 0; } } cout << endl << "输入图结构的起始点、终结点、权值:"; for(size_t i=0;i<g.e;i++){ cin >> b >> e >> w; if(w > 0 && b < g.n && e < g.n){ g.edges[b][e] = w; } else{ cout << "输入错误"; } } } void DisMatrix(Graph& g){ cout << "图的邻接矩阵:" << endl; for(size_t i=0;i<g.n;i++){ for(size_t j=0;j<g.n;j++){ cout << g.edges[i][j]<< " "; } cout << endl; } } int main(){ Graph g; Create(g); DisMatrix(g); return 0; }
2、邻接表
#include <iostream> using namespace std; #define MaxSize 100 typedef char VertexType[3]; typedef struct endgenode{ int adjvex; //邻接点序号 int value; //边的权值 struct endgenode* next; }Arcnode; //顶点包含的东西 typedef struct vexnode{ VertexType data; //节点信息 Arcnode* first; //头节点指针 }VHeadnode; typedef struct{ int n,e; //顶点数和边数 VHeadnode AdjList[MaxSize]; //表头节点数组 }Graph; void Create(Graph*& g){ int b,e,v; Arcnode* p; cout << "输入顶点数n和边数e:"; cin >> g->n >> g->e; cout << endl << "输入顶点信息:"; for(size_t i=0;i<g->n;i++){ cin >> g->AdjList[i].data; g->AdjList[i].first = NULL; } cout << endl << "输入起点号、终点号、权值:"; for(size_t i=0;i<g->e;i++){ cin >> b >> e >> v; if(v > 0 && b < g->n && e < g->n){ p = new Arcnode; p->adjvex = e; p->value = v; p->next = g->AdjList[b].first; g->AdjList[b].first = p; } else{ cout << "error for file"; } } } void DisGraph(Graph* &g){ Arcnode* p; for(size_t i=0;i<g->n;i++){ cout << "[" << i << "," << g->AdjList[i].data << "] =>"; p = g->AdjList[i].first; while(p != NULL){ cout << "(" << p->adjvex << "," << p->value << ") ->"; p = p->next; } cout << "^" << endl; } } int main(){ Graph *g; Create(g); DisGraph(g); return 0; }