从文件读取无向图邻接表函数,代码如下。在主函数中输出顶点数8后,进入循环只能输出一个1,然后就没有了。请问该如何修改?
//定义邻接表
typedef struct node{
int adjvex;//顶点编号
struct node *next;//指向下一个结点
}edgenode;//
typedef struct vnode{
int vertex;//顶点
edgenode *firstedge;//指向第一个表结点
}vertexnode,AdjList[MAX];//头结点
typedef struct{
AdjList vertices; //顶点数组
int vexnum;//顶点数
int arcnum;//弧的条数
}Graph;
int CreatGraph(Graph &G)//从文件读取并输出邻接表
{
FILE *fp;edgenode *p;
if((fp=fopen("graph.txt","r"))==NULL)
{
printf("文件打开失败\n");
return 0;
}
fscanf(fp,"%d",&G.vexnum);
G.arcnum=G.vexnum+1;
printf("顶点个数%d\n",G.vexnum);
int i,a;
for(i=1;i<=G.arcnum;i++)
{
p=(edgenode*)malloc(sizeof(edgenode));
if(fscanf(fp,"%d",&a)!=0)
{
p=(edgenode*)malloc(sizeof(edgenode));
p->adjvex=a;
p->next=G.vertices[i].firstedge;
G.vertices[i].firstedge=p;
}
}
fclose(fp);
return 1;
}
文件内容如下
8
1 2 3 0
2 1 4 5 0
3 1 6 7 0
4 2 8 0
5 2 8 0
6 3 7 0
7 3 6 0
8 4 5 0