无向图-邻接表表示

来源:互联网 发布:编程专用笔记本 编辑:程序博客网 时间:2024/05/17 09:01

初次编辑时间:2010-05-15

#include<stdio.h>#include<string.h>#include<stdlib.h>#define MAX_VERTEX_NUM 101#define VertexType int#define InfoType int#define STATUS int#define OK 1#define ERROR 0typedef enum{DG,DN,UDG,UDN}GraphKind;//{有向图,有向网,无向图,无向网}typedef struct ArcNode{    int adjvex;             //该弧所指向的顶点的位置    struct ArcNode *nextarc;//指向下一条弧的指针    InfoType *info;         //该弧相关信息的指针}ArcNode,*ANPtr;typedef struct VNode{    VertexType data;  //顶点信息    ANPtr firstarc;//指向第一条依附该顶点的弧的指针}VNode,AdjList[MAX_VERTEX_NUM];typedef struct{    AdjList vexs;    int vexnum,arcnum;//图的当前顶点数和弧数    int kind;         //图的种类的标志}ALGraph;STATUS CreateALGraph(ALGraph &G);STATUS PrintALGraph(const ALGraph &G);STATUS CalculateDegree(const ALGraph &G);STATUS DestroyALGraph(ALGraph &G);int main(void){    ALGraph G;    printf("即将构建无向图邻接表\n");    if(CreateALGraph(G))printf("无向图连接表构建成功!\n");    else printf("无向图邻接表构建失败!\n");    printf("即将输出构建的邻接表:\n");    PrintALGraph(G);    printf("即将输出个顶点的度数:\n");    CalculateDegree(G);    printf("即将销毁无向图!\n");    DestroyALGraph(G);    return 0;}STATUS CreateALGraph(ALGraph &G){    int i,u,v;    ANPtr p=NULL;    G.kind=UDG;    printf("请输入无向图的顶点数和图的边数:");    scanf("%d%d",&G.vexnum,&G.arcnum);    printf("请依次输入个顶点的值\n");    for(i=0;i<G.vexnum;i++)    {        scanf("%d",&G.vexs[i].data);        G.vexs[i].firstarc=NULL;    }    printf("请依次输入图的各弧(弧尾u、弧头v都表示该顶点的下标位置(0<=u,v<图中顶点总数))\n");    for(i=0;i<G.arcnum;i++)    {        scanf("%d%d",&u,&v);        if(!(p=(ANPtr)malloc(sizeof(ArcNode))))            {printf("内存申请失败\n");return ERROR;}        p->info=NULL;p->adjvex=v;p->nextarc=G.vexs[u].firstarc;        G.vexs[u].firstarc=p;        if(!(p=(ANPtr)malloc(sizeof(ArcNode))))            {printf("内存申请失败\n");return ERROR;}        p->info=NULL;p->adjvex=u;p->nextarc=G.vexs[v].firstarc;        G.vexs[v].firstarc=p;    }    return  OK;}STATUS PrintALGraph(const ALGraph &G){    int i;    ANPtr p=NULL;    for(i=0;i<G.vexnum;i++)    {        printf("第%3d个顶点:%d",i+1,G.vexs[i].data);        p=G.vexs[i].firstarc;        while(p){printf("->%d",G.vexs[p->adjvex].data);p=p->nextarc;}        printf("\n");    }    return OK;}STATUS CalculateDegree(const ALGraph &G){    int i,k;    ANPtr p=NULL;    for(i=0;i<G.vexnum;i++)    {        k=0;printf("第%3d个顶点:%d的度为:",i+1,G.vexs[i].data);        p=G.vexs[i].firstarc;        while(p){k++;p=p->nextarc;}        printf("%3d\n",k);    }    return OK;}STATUS DestroyALGraph(ALGraph &G){    int i;    ANPtr p=NULL,q=NULL;    for(i=0;i<G.vexnum;i++)    {        p=G.vexs[i].firstarc;        while(p){q=p;p=p->nextarc;free(q);}    }    return OK;}

0 0
原创粉丝点击