zoukankan      html  css  js  c++  java
  • 数据结构----图(邻接表用法)

    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
    ",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("
    ");
    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:
    ");
     8     outPut(lg);
     9     free(lg); 
    10     getch();
    11     return 0;
    12 }
    View Code
  • 相关阅读:
    day13—— luffy项目 User表的配置
    day13 —— luffy项目 数据库配置
    day13- luffy项目 后端搭建
    Vue环境搭建
    Python创建虚拟环境
    pip换源
    day12--DRF 进阶7 JWT补充、基于权限的角色控制、django缓存
    C语言输出格式总结-printf()
    PAT 甲级 1108 Finding Average (20分)
    DAY30
  • 原文地址:https://www.cnblogs.com/hoojjack/p/4565729.html
Copyright © 2011-2022 走看看