{/'title/':/'C语言图数据结构邻接链表创建及打印代码优化修复/',/'description/':/'本文修复了C语言中使用邻接链表创建图的代码逻辑错误,并优化了打印图的代码。修复后的代码能够正确创建和打印图的邻接链表。/',/'keywords/':/'C语言, 图数据结构, 邻接链表, 代码修复, 优化/',/'content/':/'void creategraph(adjgraph *&G, int A[maxv][maxv] ,int n ) {//n//tG=(adjgraph *)malloc(sizeof(adjgraph));//n//tint i,j;//n//tanode *p;//n//tfor(i=0; i<n; i++)//n//t/tG->adjlist[i].firstarc=NULL;//n//tfor(i=0; i<n; i++) {//n//t/tfor(j=n-1; j>=0; j--) {//n//t/t/tif(A[i][j]!=0&&A[i][j]!=inf) {//n//t/t/t/tp=(anode *)malloc(sizeof(anode));//n//t/t/t/tp->adjvex=j;//n//t/t/t/tp->weight=A[i][j];//n//t/t/t/tp->nextarc=G->adjlist[i].firstarc;//n//t/t/t/tG->adjlist[i].firstarc=p;//n//t/t/t}//n//t/t}//n//t}//n//tG->n=n;//n}//n//nvoid printgraph(adjgraph *G ) {//n//tint i;//n//tanode *p;//n//tfor(i=0; in; i++) {//n//t/tp=G->adjlist[i].firstarc;//n//t/tprintf(/'%3d/',i);//n//t/twhile(p!=NULL) {//n//t/t/tprintf(/'%3d[%d]/',p->adjvex,p->weight);//n//t/t/tp=p->nextarc;//n//t/t}//n//t/tprintf(/'^/n/');//n//t}//n}//n修复内容:在函数creategraph中,修复了一个错误的逻辑错误。修复后的代码如下://n//nvoid creategraph(adjgraph *&G, int A[maxv][maxv] ,int n ) {//n//tG=(adjgraph *)malloc(sizeof(adjgraph));//n//tint i,j;//n//tanode *p;//n//tfor(i=0; i<n; i++)//n//t/tG->adjlist[i].firstarc=NULL;//n//tfor(i=0; i<n; i++) {//n//t/tfor(j=n-1; j>=0; j--) {//n//t/t/tif(A[i][j]!=0&&A[i][j]!=inf) {//n//t/t/t/tp=(anode *)malloc(sizeof(anode));//n//t/t/t/tp->adjvex=j;//n//t/t/t/tp->weight=A[i][j];//n//t/t/t/tp->nextarc=G->adjlist[i].firstarc;//n//t/t/t/tG->adjlist[i].firstarc=p;//n//t/t/t}//n//t/t}//n//t}//n//tG->n=n;//n}//n//n修复后的代码中,将if语句括号内的代码块包裹起来,确保只有当条件满足时才执行相关的代码。修复后的代码将正确地创建了图的邻接链表。//n//n另外,在函数printgraph中,将for循环的结束条件改为in,而不是固定的3。这样可以确保遍历所有的顶点。修复后的代码如下://n//nvoid printgraph(adjgraph *G ) {//n//tint i;//n//tanode *p;//n//tfor(i=0; in; i++) {//n//t/tp=G->adjlist[i].firstarc;//n//t/tprintf(/'%3d/',i);//n//t/twhile(p!=NULL) {//n//t/t/tprintf(/'%3d[%d]/',p->adjvex,p->weight);//n//t/t/tp=p->nextarc;//n//t/t}//n//t/tprintf(/'^/n/');//n//t}//n}//n//n修复后的代码将正确地打印图的邻接链表。/

C语言图数据结构邻接链表创建及打印代码优化修复

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

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