邻接表输出为什么出错?
程序代码:
#include <stdio.h> #include <stdlib.h> #include <assert.h> #define MAX_VERTEX_NUM 10 typedef struct ArcNode{ int adjvex;//该边的另一个顶点的位置 struct ArcNode *nextarc; //指向下一条边 }ANode; typedef struct VexNode{ int data;//顶点的值 ANode *firstarc;//指向第一条依附该顶点的边的指针 }AdjList; typedef struct Graph{ AdjList vertices[MAX_VERTEX_NUM];//顶点数组 int vexnum, arcnum; }ALGraph; int LocateVex(ALGraph G, int v) //定位函数 { int i; for(i=0; i < G.vexnum; i++) if(v == G.vertices[i].data) return i; if(i == G.vexnum){ printf("顶点错误!"); exit(1); } } void CreateUDG(ALGraph G) { ANode *p,*q; int i,j,k,v1,v2; printf("分别输入顶点个数和边的数目:\n"); scanf("%d%d", &G.vexnum, &G.arcnum); while(getchar() != '\n') continue; printf("分别输入各个顶点值:\n"); for(i=0; i < G.vexnum; i++){ scanf("%d", &G.vertices[i].data); G.vertices[i].firstarc = NULL;//初始化 } while(getchar() != '\n') continue; printf("分别输入各条边的两个顶点:\n"); for(k = 0; k < G.arcnum; k++){ scanf("%d%d", &v1, &v2); i = LocateVex(G,v1); //定位 j = LocateVex(G,v2); p = (ANode*)malloc(sizeof(ANode));//申请一个结点 assert(p); p->adjvex = j;//赋值 p->nextarc = G.vertices[i].firstarc;//连接后结点 G.vertices[i].firstarc = p;//连接前结点 q = (ANode*)malloc(sizeof(ANode)); assert(p); q->adjvex = i; q->nextarc = G.vertices[j].firstarc; G.vertices[j].firstarc = q; } } void PrintUDG(ALGraph G) //输出邻接表 { int m; for(m=0; m < G.vexnum; m++){ printf("%d:", m); ANode *p; p = G.vertices[m].firstarc; while(p != NULL){ printf("->%d", p->adjvex); //此处出现错误!!! p = p->nextarc; } printf("\n"); } } int main(void) { ALGraph G; CreateUDG(G); PrintUDG(G); return 0; }