C语言实现矩阵图和邻接表图的创建与打印
{"title":"C语言实现矩阵图和邻接表图的创建与打印","description":"本代码使用 C 语言实现了矩阵图和邻接表图的创建与打印功能,并提供了详细的代码注释,方便理解和学习。","keywords":"C语言, 矩阵图, 邻接表图, 图论, 数据结构, 代码实现","content":"#include\u003cstdio.h\u003e\n#include\u003cstring.h\u003e\n#include\u003cstdlib.h\u003e\n#define maxv 10\n#define inf 32767\ntypedef char infotype;\ntypedef struct {\n int no;\n infotype *info;\n} vertextype;\ntypedef struct {\n int edges[maxv][maxv];\n vertextype vexs[maxv];\n int n;\n int e;\n} matgraph;\n\nvoid creatematgraph(matgraph *\u0026T, int n,int \u0026e) {\n e=0;\n T = (matgraph *)malloc(sizeof(matgraph)); \n infotype ch[10];\n int k = 0, i = 0, j = 0;\n int r;\n while (k \u003c n) {\n scanf("%s", ch);\n T->vexs[k].no = k;\n T->vexs[k].info = new char[strlen(ch) + 1]; // 分配足够的内存\n strcpy(T->vexs[k].info, ch);\n k++;\n }\n while (i \u003c n) {\n j = 0;\n while (j \u003c n) {\n printf("Is the edge [%d][%d] exist?\n", i, j);\n scanf("%d", \u0026r);\n T->edges[i][j] = r;\n if(r!=0)e++;\n j++;\n }\n i++;\n }\n}\n\nvoid printgraph(matgraph *\u0026T, int n,int e) {\n int k = 0;\n while (k \u003c n) {\n printf("No%d:%s\n", T->vexs[k].no, T->vexs[k].info);\n k++;\n }\n int i = 0, j = 0;\n while (i \u003c n) {\n j = 0;\n while (j \u003c n) {\n printf("%d\t", T->edges[i][j]);\n j++;\n }\n printf("\n");\n i++;\n }\n}\n\n\ntypedef struct anode\n{\n int adjvex;\n struct anode *nextarc;\n int weight;\n} anode;\ntypedef struct vnode\n{\n infotype info;\n anode *firstarc;\n} vnode;\ntypedef struct\n{\n vnode adjlist[maxv];\n int n,e;\n}adjgraph;\n\nvoid creategraph(adjgraph *\u0026G, int A[maxv][maxv],int n ,int e)\n{\n G=(adjgraph *)malloc(sizeof(adjgraph));\n int i,j;\n anode *p;\n for(i=0;i\u003cn;i++)\n G->adjlist[i].firstarc=NULL;\n for(i=0;i\u003cn;i++){\n for(j=n-1;j\u003e=0;j--)\n {\n if(A[i][j]!=0\u0026\u0026A[i][j]!=inf){\n p=(anode *)malloc(sizeof(anode));\n p->adjvex=j;\n p->weight=A[i][j];\n p->nextarc=G->adjlist[i].firstarc;\n G->adjlist[i].firstarc=p;\n }\n }\n }\n G->n=n;\n G->e=e; \n}\n\nvoid printgraph(adjgraph *G )\n{\n int i;\n anode *p;\n for(i=0;i\u003cG->n;i++)\n {\n p=G->adjlist[i].firstarc;\n printf("%d",i);\n while(p!=NULL)\n {\n printf("%3d[%d]",p->adjvex,p->weight);\n p=p->nextarc;\n }\n printf("^\n");\n }\n}\n\nint main()\n{\n matgraph *T;\n adjgraph *G;\n int n = 3;\n int e;\n creatematgraph(T, n,e);\n printgraph(T, n,e); \n int B[maxv][maxv];\n for(int i=0;i\u003cn;i++){\n for(int j=0;j\u003cn;j++){\n B[i][j]=T->edges[i][j];\n }\n }\n creategraph(G, B,n ,e);\n printgraph(G);\n return 0;\n}
原文地址: https://www.cveoy.top/t/topic/qf8I 著作权归作者所有。请勿转载和采集!