一步两步学算法之图邻接表实现

图的邻接表实现 

这种结构创建邻接表时添加节点较为绕 建议断点调试下看看

邻接表和邻接矩阵相比 邻接表节省空间但是很难判断两个节点之间是否有边  此种结构要在稀疏图下才划算

下面是代码

 1 #define VERTEX_MAX 20

 2 #include "stdio.h"

 3 #include "malloc.h"

 4 typedef struct edgeNode

 5 {

 6     int Vertex;                //顶点序号 

 7     int weight;

 8     struct edgeNode *next;    //指向有边的下一个顶点 

 9 }EdgeNode;                    //邻接表边的结构 

10 

11 typedef struct

12 {

13     EdgeNode *AdjList[VERTEX_MAX];                //顶点的结构体指针数组 

14     int VextexNum,EdgeNum;                        //顶点数量 边的数量 

15     int GraphType;                                //图的类型 

16     

17 }ListGraph;                                    //邻接表结构 

18 void CreateGraph(ListGraph *G);                //创建邻接表 

19 void OutList(ListGraph);                    //输出邻接表 

20 

21 void CreateGraph (ListGraph *G)

22 {

23     int i,weight;

24     int start,end;

25     EdgeNode *s;

26     for(i=1;i<=G->VextexNum;i++)

27         G->AdjList[i]=NULL;                        //所有顶点初始化为NULL 

28     for(i=1;i<=G->EdgeNum;i++)

29     {

30         getchar();

31         printf("第%d条边:",i);

32         scanf("%d%d%d",&start,&end,&weight);

33         s=(EdgeNode*)malloc(sizeof(EdgeNode));            //申请保存一条边的内存 

34         s->next=G->AdjList[start];                        //指向上一个顶点所在位置 

35         s->Vertex=end;                                    // 保存结束顶点 

36         s->weight=weight;                                    

37         G->AdjList[start]=s;                            //邻接表对应该点指向该点            

38         if(G->GraphType==0)

39         {

40             s=(EdgeNode *)malloc(sizeof(EdgeNode));

41             s->next=G->AdjList[end];

42             s->Vertex=start;

43             s->weight=weight;

44             G->AdjList[end]=s;

45         }

46     }

47 } 

48 

49 void OutList(ListGraph *G)

50 {

51     int i;

52     EdgeNode *s;

53     for(i=1;i<=G->VextexNum;i++)

54     {

55         printf("顶点%d",i);

56         s=G->AdjList[i];

57         while(s)

58         {

59             printf("->%d(%d)",s->Vertex,s->weight);

60             s=s->next;

61         }

62         printf("\n");

63     }

64 }

65 main()

66 {

67     ListGraph G;

68     printf("输入生成图的类型(0.无向图,1.有向图)");

69     scanf("%d",&G.GraphType);

70     printf("输入图的顶点数量和边数量");

71     scanf("%d%d",&G.VextexNum,&G.EdgeNum);

72     printf("输入构成各边的两个顶点及权值:\n");

73     CreateGraph(&G);

74     printf("输出邻接表\n");

75     OutList(&G);

76     return 0; 

77 }

 

你可能感兴趣的:(算法)