邻接表存储图的结构并实现在指定节点开始的深度优先遍历,为什么运行程序输到第五条边的时候就出现错误啊!
程序代码:
#include <stdio.h> #include <stdlib.h> #define MAX_VERTEX_NUM 20 #define MAX 20 int visited[MAX]; typedef struct ArcNode{ int adjvex; struct ArcNode *next; }ArcNode; typedef struct VNode{ int data; ArcNode * firstarc; }VNode,AdjList[MAX_VERTEX_NUM]; typedef struct{ AdjList vertices; int vexnum ,arcnum; }ALGraph; void Init_ALGraph(ALGraph *a) { int V1,V2,S; ArcNode *p; int m,i,j; printf("请分别输入图的顶点数和边数:\n"); scanf("%d",&i); scanf("%d",&j); a->vexnum=i; a->arcnum=j; printf("请输入各节点数据\n"); for(i=0;i<a->vexnum;i++) { scanf("%d",&(a->vertices[i].data)); (a->vertices[i]).firstarc=NULL; } for(S=1;S<=a->arcnum;S++) { printf("请输一条边的两个顶点的数据:\n"); scanf("%d",&V1); scanf("%d",&V2); for(i=0;V1!=a->vertices[i].data;i++); for(j=0;V2!=a->vertices[j].data;j++); p=(ArcNode *)malloc(sizeof(ArcNode)); p->adjvex=j; p->next=a->vertices[i].firstarc; a->vertices[i].firstarc=p; p=(ArcNode *)malloc(sizeof(ArcNode)); p->adjvex=i; p->next=a->vertices[j].firstarc; a->vertices[j].firstarc=p; } } void DFS(ALGraph a,int v) { ArcNode *L; visited[v]=1; printf("深度优先遍历次序为:%d\t",a.vertices[v].data); for(L=a.vertices[v].firstarc;L!=NULL;L=L->next) { DFS(a,L->adjvex); } } void DFSTraverse(ALGraph a) { int v,m; for(v=0;v<a.vexnum;++v) visited[v]=0; printf("请输入最先遍历的节点数据:\n"); scanf("%d",&v); for(m=0;a.vertices[m].data!=v;m++); for(v=m;v<a.vexnum;v++) if(!visited[v]) DFS(a,v); for(v=0;v<m;v++) if(!visited[v]) DFS(a,v); } int main() { ALGraph a; printf("邻接表存储图的结构\n"); Init_ALGraph(&a); printf("深度优先遍历图显示如下:\n"); DFSTraverse(a); return 0; }