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
  • 相关阅读:
    字符编码笔记:ASCII,Unicode 和 UTF-8
    nginx 负载均衡设置
    ubuntu 修改时区
    js 高阶函数 filter
    js 高阶函数 map reduce
    省市联级菜单--js+html
    php代码优化技巧
    json、xml ---- 数据格式生成类
    初识设计模式(1)---单例、工厂、注册树
    php 链式操作的实现 学习记录
  • 原文地址:https://www.cnblogs.com/hoojjack/p/4565729.html
Copyright © 2011-2022 走看看