主题:建立和输出有向图的邻接表的问题
#include "stdio.h"
#define MAXVER 10
#define NULL 0
struct node
{int vertex;
struct node *next;
};
typedef struct node adjlist[MAXVER];/*定义顶点数组*/
creagraph(adjlist g,int*n)
{int e,i,s,d;
struct node *p,*q;
scanf("%d%d",n,&e); /*输入结点数和边树*/
for(i=1;i<=*n;i++)
{g[i].vertex=i; /*表头结点初始化*/
g[i].next=NULL;
}
for(i=1;i<=e;i++)
{scanf("%d%d",&s,&d);/*输入边和结点*/
p=(struct node*)malloc(sizeof(struct node));
p->vertex=d;
p->next=NULL;
q=&g[s];
while(q->next!=NULL) /*找到该顶点的头*/
q=q->next;
q->next=p;
}}
printgraph(adjlist g,int n) /*输出邻接表*/
{int i;
struct node *p;
for (i=1;i<=n;i++)
{p=g[i].next;
printf("[%d]",i);
while(p!=NULL)
{printf("%d-->",p->vertex);
p=p->next;
}
printf("\n");
}
}
main()
{
adjlist g ;
int n;
creagraph(g, &n);
printgraph( g,n);
}
怎么会得不到想要的结果?
#define MAXVER 10
#define NULL 0
struct node
{int vertex;
struct node *next;
};
typedef struct node adjlist[MAXVER];/*定义顶点数组*/
creagraph(adjlist g,int*n)
{int e,i,s,d;
struct node *p,*q;
scanf("%d%d",n,&e); /*输入结点数和边树*/
for(i=1;i<=*n;i++)
{g[i].vertex=i; /*表头结点初始化*/
g[i].next=NULL;
}
for(i=1;i<=e;i++)
{scanf("%d%d",&s,&d);/*输入边和结点*/
p=(struct node*)malloc(sizeof(struct node));
p->vertex=d;
p->next=NULL;
q=&g[s];
while(q->next!=NULL) /*找到该顶点的头*/
q=q->next;
q->next=p;
}}
printgraph(adjlist g,int n) /*输出邻接表*/
{int i;
struct node *p;
for (i=1;i<=n;i++)
{p=g[i].next;
printf("[%d]",i);
while(p!=NULL)
{printf("%d-->",p->vertex);
p=p->next;
}
printf("\n");
}
}
main()
{
adjlist g ;
int n;
creagraph(g, &n);
printgraph( g,n);
}
怎么会得不到想要的结果?