数据结构之用邻接表实现树

来源:互联网 发布:电脑办公软件大全 编辑:程序博客网 时间:2024/05/16 13:04

原始图


邻接表


代码

#include "stdio.h"
#include "stdlib.h"
#define AdjType float
#define VexType char
#define vex_num 5
/*
实现功能:用邻接表的方法存储图
编译环境:win7 64b,vc6.0
日期 :2015/8/7
作者 :wtt561111
*/


typedef struct EdgeNode *PEdgeNode;
typedef struct EdgeNode *EdgeList;
struct EdgeNode{ //字表中的节点
int endvex; //末点对应的表下标
AdjType weight;//权重
PEdgeNode nextedge;//下一个邻接的点
};
typedef struct EdgeNode *PEdgeNode;
struct VexNode {
VexType vertex;//顺序表中存储的点的信息
EdgeList edgelist;//指向末点
};
typedef struct VexNode *PVexNode;
struct GraphList{ //表示一个图
int n; //图中有n个点
VexNode *vexs;//指向一个顺序表
};
typedef struct GraphList *PGraphList;
/*
创建一个链表中的节点。成功返回节点指针,否则返回NULL
*/
PEdgeNode createNode_GrapgList(VexType position,PEdgeNode link){
PEdgeNode node=(PEdgeNode)malloc(sizeof(struct EdgeNode));
if(node==NULL){
printf("out of space\n");
return NULL;
}
node->endvex=position;
node->nextedge=link;
return node;
}
/*****************主函数***********************************************/
int main(){
//创建一个树
PGraphList gl=(PGraphList)malloc(sizeof(struct GraphList));
if(gl==NULL){
printf("out of space\n");
return NULL;
}


//创建顺序表
PVexNode vex=(PVexNode)malloc(sizeof(struct VexNode)*vex_num);


//初始化顺序表
vex[0].vertex='0';
PEdgeNode node01=createNode_GrapgList(1,NULL);
vex[0].edgelist=node01;
vex[1].vertex='1';
PEdgeNode node14=createNode_GrapgList(4,NULL);
PEdgeNode node10=createNode_GrapgList(0,node14);
vex[1].edgelist=node10;
vex[2].vertex='2';
PEdgeNode node23=createNode_GrapgList(3,NULL);
PEdgeNode node21=createNode_GrapgList(1,node23);
vex[2].edgelist=node21;
vex[3].vertex='3';
PEdgeNode node30=createNode_GrapgList(0,NULL);
vex[3].edgelist=node30;
vex[4].vertex='4';
PEdgeNode node43=createNode_GrapgList(3,NULL);
vex[4].edgelist=node43;


//将顺序表的信息复制到图中
gl->vexs=vex;
gl->n=5;


//输出第一个点的信息以及构成的边
int v0_edge1_postion=gl->vexs[0].edgelist->endvex;
printf("v%c\tv%c\n",gl->vexs[0].vertex,gl->vexs[v0_edge1_postion].vertex);
return 0;
}

0 0
原创粉丝点击