1、定义图的结构:

 1 #define NUM_MAX 6
 2 typedef struct ArcNode{
 3     int adjvex;
 4     struct ArcNode * nextArc;
 5 }ArcNode; //定义弧结点结构体
 6 typedef struct VertexNode{
 7     int data;
 8     ArcNode * firstArc;
 9 }VertexNode;//定义顶点结构体
10 typedef struct {
11     VertexNode * AdjList[NUM_MAX];
12     int vertexNum,edgeNum;
13     int graphType;
14 }LinkGraph;//定义图

2、定义创建图的邻接表的函数

 1 void createLink(LinkGraph *lg){
 2     int start,end;
 3     ArcNode *s;
 4     for(int i=1;i<=lg->vertexNum;i++){
 5         (lg->AdjList[i])=(VertexNode *)malloc(sizeof(VertexNode));//如果这里没有开辟内存空间,则lg->AdjList[i]是空的。这是指针变量与实体变量的区别
 6         (lg->AdjList[i])->data=i;
 7         (lg->AdjList[i])->firstArc=NULL;
 8     }
 9     for(int i=1;i<=lg->edgeNum;i++){
10         printf("Please input two vertexes of the %dth edge\n",i);
11         scanf("%d%d",&start,&end);
12         s=(ArcNode *)malloc(sizeof(ArcNode));
13         s->adjvex=end;
14         s->nextArc=lg->AdjList[start]->firstArc;
15         lg->AdjList[start]->firstArc=s;
16     }
17 }

3、定义输出邻接表函数

 1 void outPut(LinkGraph *lg){
 2     ArcNode *s;
 3     for(int i=1;i<=lg->vertexNum;i++){
 4         printf("the vertex %d:",i);
 5         s=lg->AdjList[i]->firstArc;
 6         while(s){
 7             printf(" --> %d",s->adjvex);
 8             s=s->nextArc;
 9         }
10         printf("\n");
11     }
12     
13 }

4、主函数:

 1 int main(){
 2     LinkGraph *lg;
 3     lg=(LinkGraph*)malloc(sizeof(LinkGraph));
 4     printf("Please input the vertexNum and edgeNum:");
 5     scanf("%d%d",&lg->vertexNum,&lg->edgeNum);
 6     createLink(lg);
 7     printf("Output the LinkGraph:\n");
 8     outPut(lg);
 9     free(lg); 
10     getch();
11     return 0;
12 }
View Code