一:数组表示法
#include #define maxn 100#define INFINITY 0typedef struct{ int vexs[maxn]; int arcs[maxn][maxn]; int vexnum, arcnum;//vexnum为顶点数,arcnum为边数}Graph;void init(Graph &g) //需要传递g的地址使g改变{ puts("Enter the vexnume and arcnum"); scanf("%d%d", &g.vexnum, &g.arcnum); puts("Enter the vertex"); for (int i = 0; i < g.vexnum; i++) scanf("%d", &g.vexs[i]); //构造顶点向量 for (int i = 0; i < g.vexnum; i++) for (int j = 0; j < g.vexnum; j++) g.arcs[i][j] = INFINITY; //用无限表示没有这条边,现在用0打印清楚一点}int locate(Graph &g, int v) //寻找位置,有时顶点不一定是数字而且次序也可能打乱输入{ int i; for (i = 0; i < g.vexnum; i++) if (g.vexs[i] == v) return i;}void create(Graph &g){ int v1, v2, w,i,j,k; for (k = 0; k< g.arcnum; k++) { puts("Enter the two vertexs of the edge and the value"); scanf("%d%d%d", &v1, &v2, &w); //输入一条边依附的顶点和权值 i = locate(g, v1); j = locate(g, v2); g.arcs[i][j] = g.arcs[j][i]=w; //无向网 }}void print(Graph &g){ for (int i = 0; i < g.vexnum; i++) { for (int j = 0; j < g.vexnum; j++) printf("%d ", g.arcs[i][j]); printf("\n"); }}int main(){ Graph g; init(g); create(g); print(g); return 0;}
二:邻接表
#include #include #define maxn 20typedef struct node //弧的定义{ int adjvex; //该弧指向的顶点 struct node *next; int data;}node;typedef struct vnode{ int data; node *first;}vnode,adjust[maxn];typedef struct{ adjust vertices; int vexnum, arcnum;}graph;void build(graph *g){ puts("Enter the vexnum and arcnum"); scanf("%d%d", &g->vexnum, &g->arcnum); int i; for (i = 0; i < g->vexnum; i++) { printf("Enter very vertices of the list\n"); scanf("%d", &g->vertices[i].data); g->vertices[i].first= NULL; } puts("Establish every list"); for (int k = 0; k < g->arcnum; k++) { int v1, v2; printf("Enter the edge:(v1,v2)\n"); scanf("%d%d", &v1, &v2); node *s = (node *)malloc(sizeof(node)); s->adjvex = v2; s->next = g->vertices[v1].first; g->vertices[v1].first = s; //倒序插入链表 s = (node *)malloc(sizeof(node));//无向图两边都要写 s->adjvex = v1; s->next = g->vertices[v2].first; g->vertices[v2].first = s; }}void print(graph *g){ for (int i = 0; i < g->vexnum; i++) { printf("%d->", i); while (g->vertices[i].first != NULL) { printf("%d->", g->vertices[i].first->adjvex); g->vertices[i].first = g->vertices[i].first->next; } printf("\n"); }}int main(){ graph *g=(graph *)malloc(sizeof(graph)); build(g); print(g); return 0;}