#include "stdio.h"
typedef struct ArcNode{
/*单链表中的结点的类型*/
int adjvex; /*该边指向的顶点在顺序表中的位置*/
struct ArcNode *next; /*下一条边*/
}ArcNode;
typedef struct VNode{
/*顶点类型*/
int data; /*顶点中的数据信息*/
ArcNode *firstarc; /*指向单链表,即指向第一条边*/
}VNode;
int visited[5]={0,0,0,0,0};
CreatGraph(int n , VNode G[] ){
int i,e;
ArcNode *p , *q;
printf("Input the information of the vertex\n");
for(i=0;i<n;i++){
scanf("%d",&G[i]);
G[i].firstarc = NULL; /*初始化第一条边为空*/
}
for(i=0;i<n;i++){
printf("Creat the edges for the %dth vertex\n",i) ;
scanf("%d",&e);
while(e!=-1){
p = (ArcNode *)malloc(sizeof(ArcNode)); /*创建一条边*/
p->next = NULL;
p->adjvex = e;
if(G[i].firstarc == NULL) G[i].firstarc = p; /*i结点的第一条边*/
else q->next = p; /*下一条边*/
q = p;
scanf("%d",&e);
}
}
}
这是邻接表的部分代码。为什么创建边时p要malloc(对应 p = (ArcNode *)malloc(sizeof(ArcNode)); ),而q直接用就行?