实现图的邻接矩阵存储和邻接表存储转换

/*
   实现图的邻接矩阵存储和邻接表存储
*/ 
#include "stdio.h"
#include "malloc.h"
#define MAXV 5//结点个数 

typedef struct matGraph{
	int egdes[MAXV][MAXV];
	int n;//顶点数 
	int e;//边数 
	char vexs[5][3];//存v0,v1,v2,v3,v4,存串的时候要加上\0,所以是3 
}MatGraph;

typedef struct ANode{
	//边
	int adjvex;//V0--V4的存储位置 
	struct ANode * nextarc; //下一条边 
}ArcNode;

typedef struct Vnode{
	char data[3];
	ArcNode * firstarc;
}VNode;//顶点 

typedef struct {
	VNode adjlist[MAXV];
	int n;
	int e;
}AdjGraph; 

main(){
	MatGraph mG = {
		             {
		             	{0,1,0,1,1},
		             	{1,0,1,1,0},
		             	{0,1,0,1,1},
		             	{1,1,1,0,1},
		             	{1,0,1,1,0},
					 },
					 5,
					 8,
					 {
					 	{"V0\0"},
					 	{"V1\0"},
					 	{"V2\0"},
					 	{"V3\0"},
					 	{"V4\0"},
					 }
					 
	              };
	int i;
	int j;
	AdjGraph aG;
	ArcNode * arc;
	
	printf("vexnum:%d\n",mG.n );
	printf("edgnum:%d\n",mG.e);
	printf("i: 0   1   2   3   4\n");
	for(i=0;i<MAXV;i++){
		for(j=0;j<MAXV;j++){
			printf("%4d",mG.egdes[i][j]);
		}
		printf("\n");
	}
	
	aG.e = mG.e ;
	aG.n = mG.n;
	for(i=0;i<MAXV;i++){
		for(j=0;j<3;j++){
			aG.adjlist[i].data[j]=mG.vexs[i][j];
			aG.adjlist[i].firstarc = NULL;
		}
	}
	
	for( i=0;i<MAXV;i++){
		for(j=0;j<MAXV;j++){
			if(mG.egdes[i][j]!=0){
				arc=(ArcNode *)malloc(sizeof(ArcNode));
				arc->adjvex = j;
				//插入到aG.adjlist[i]firstarc后面
				arc->nextarc=aG.adjlist[i].firstarc;
				aG.adjlist[i].firstarc=arc; 
			}
		}
	}
	
	printf("*****************\n");
	printf("vexnum:%d\n",aG.n);
	printf("degnum:%d\n",aG.e);
	for(i=0;i<MAXV;i++){
		printf("%s",aG.adjlist[i].data );
		arc = aG.adjlist[i].firstarc ;
		while(arc!=NULL){
			printf("%4d",arc->adjvex);
			arc=arc->nextarc;
		}
		printf("\n");
	}
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值