#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct node{ //定义结点结构 由数据域vertex和指针域next组成
int vertex;
struct node *next;
}NODE;
typedef struct hnode{ //定义头结点结构 由数据域head和 指针域first组成 !!!注意 !!! 指针域类型是node 而不是hnode!!!
int head;
struct node *first;
}HNODE;
typedef struct{ //定义邻接表的结构 由头结点数组 和头结点数n边数e组成 !!!注意 !!!头结点数组存放的是头结点 而不是头结点指针!!
HNODE list[10];
int n,e;
}GRAPH;
void create(GRAPH *G);
int main(){
int i,j;
GRAPH *G=(GRAPH *)malloc(sizeof(GRAPH)); //定义一个邻接表的指针 不要忘记分配动态内存单元
create(G); //传入邻接表指针 创建邻接表
for(i=0;i<G->n;i++)
{
printf("%d->",i);
while(G->list[i].first!=NULL)
{
printf("%d->",G->list[i].first->vertex);
G->list[i].first=G->list[i].first->next;
}
printf("\n");
}
return 0;
}
void create(GRAPH *G){
int p,q,i,j,m;
NODE *s;
printf("请输入定点数n和边数e:");
scanf("%d %d",&G->n,&G->e);
for(p=0;p<G->n;p++)
{
printf("请输入头节点:"); //初始化头结点
scanf("%d",&m);
G->list[m].head=m;
G->list[m].first=NULL;
}
for(q=0;q<G->e;q++)
{
printf("请输入边Vi Vj:");
scanf("%d %d",&i,&j);
s=(NODE *)malloc(sizeof(NODE));
s->vertex=j;
s->next=G->list[i].first;
G->list[i].first=s;
s=(NODE *)malloc(sizeof(NODE));
s->vertex=i;
s->next=G->list[j].first;
G->list[j].first=s;
}
}
运行结果: