#include <stdio.h> #include <stdlib.h>

#define maxv 100 // 定义最大顶点数

typedef int infotype; // 定义顶点的类型

typedef struct anode { int adjvex; struct anode *nextarc; int weight; } anode;

typedef struct vnode { infotype info; anode *firstarc; } vnode;

typedef struct { vnode adjlist[maxv]; int n, e; } adjgraph;

void creatematgraph(adjgraph *&G, int A[maxv][maxv], int n, int e) { G = (adjgraph *)malloc(sizeof(adjgraph)); int i, j; anode *p; for (i = 0; i < n; i++) G->adjlist[i].firstarc = NULL; for (i = 0; i < n; i++) { for (j = n - 1; j >= 0; j--) { if (A[i][j] != 0 && A[i][j] != -1) { p = (anode *)malloc(sizeof(anode)); p->adjvex = j; p->weight = A[i][j]; p->nextarc = G->adjlist[i].firstarc; G->adjlist[i].firstarc = p; } } } G->n = n; G->e = e; }

void printgraph(adjgraph *G) { int i; anode *p; for (i = 0; i < G->n; i++) { p = G->adjlist[i].firstarc; printf("%d", i); while (p != NULL) { printf(" -> %d(%d)", p->adjvex, p->weight); p = p->nextarc; } printf(" -> NULL\n"); } }

int main() { int n = 3; int e = 3; int A[maxv][maxv] = {{0, 1, 2}, {1, 0, 3}, {2, 3, 0}}; adjgraph *G; creatematgraph(G, A, n, e); printgraph(G);

return 0;
#includematgraphcpptypedef struct anode	int adjvex;	struct anode nedxarc;	int weight; anode;typedef struct vnode	infotype info;	anode firstarc; vnode;typedef struct	vnode adjlistmaxv;	int ne;adjgraph;

原文地址: http://www.cveoy.top/t/topic/iyXy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录