图的邻接矩阵和邻接表表示,及相互之间的转换

第一次发文,还请各路大神指教。程序是对照《数据结构教程上机实验指导》写的,请指教。哭辛苦排的版还是显示不出来,摸索ing。。。。

#include <stdio.h>
#include <malloc.h>
typedef int InfoType;
#define MAXV 50

//图的邻接矩阵表示
typedef struct VertType
{
	int no;
	InfoType info;
}VertType;

typedef  struct 
{
	int edges[MAXV][MAXV];
	int n,e;
	VertType vexs[MAXV];
}MGraph;

//图的邻接表表示
typedef struct ANode
{
	int adjvex;
	struct ANode *nextarc;
	InfoType info;
}ArcNode;

typedef int Vertex;

typedef struct VNode
{
	Vertex data;
	ArcNode *firstarc;
}VNode;

typedef VNode AdjList[MAXV];

typedef struct 
{
	AdjList adjlist;
	int n,e;
}ALGraph;
//输出图的邻接矩阵
void DispMat(MGraph g)
{
	int i,j,n=g.n;
	for(i=0; i<n; i++)
	{
		for(j=0; j<n; j++)
		{
			if(g.edges[i][j] == INF)
				printf("%3d","∞");
			else
				printf("%3d",g.edges[i][j]);
		}
		printf("\n");
	}
}
//输出图的邻接表
void DispAdj(ALGraph *G)
{
	int i,n=G->n;
	ArcNode *p;
	for(i=0; i<n; i++)
	{
		p = G->adjlist[i].firstarc;
		if(p)
			printf("%3d:",i);
		while(p)
		{
			printf("%3d",p->adjvex);
			p = p->nextarc;
		}
		printf("\n");
	}
}
//邻接矩阵转化为邻接表表示
void MatToList (MGraph g, ALGraph *&G)
{
	int i,j,n=g.n;
	ArcNode *p;
	G = (ALGraph *)malloc(sizeof(ALGraph));
	for(i=0; i<n; i++)			
	{
		G->adjlist[i].firstarc = NULL;
	}
	for(i=0; i<n; i++)
	{
		for(j=n-1; j>=0; j--)
		{
			if(g.edges[i][j] != 0)
			{
				p = (ArcNode *)malloc(sizeof(ArcNode));
				p->adjvex = j;
				p->info = g.edges[i][j];
				p->nextarc = G->adjlist[i].firstarc;	
				G->adjlist[i].firstarc = p;
			}
		}
	}
	G->n = n;
	G->e = g.e;
}
//邻接表转化为邻接矩阵表示
MGraph ListToMat(ALGraph *G, MGraph g)
{
	int i,j,n=G->n;
	ArcNode *p;
	for(i=0; i<n; i++)
		for(j=0; j<n; j++)
			g.edges[i][j] = 0;
	for(i=0; i<n; i++)
	{
		p = G->adjlist[i].firstarc;
		while(p)
		{
			g.edges[i][p->adjvex] = p->info;
			p = p->nextarc;
		}
	}
	g.n = n;
	g.e = G->e;
	return g;
}

void main()
{
	int i,j;
	MGraph g,g1;
	ALGraph *G;
	int A[MAXV][6] = {
		{0,5,0,7,0,0},
		{0,0,4,0,0,0},
		{8,0,0,0,0,9},
		{0,0,5,0,0,6},
		{0,0,0,5,0,0},
		{3,0,0,0,1,0}
	};
	g.n = 6;
	g.e = 10;
	for(i=0; i<g.n; i++)
		for(j=0; j<g.n; j++)
		{
			g.edges[i][j] = A[i][j];
		}
	printf("\n");
	printf("输出邻接矩阵表示的图g:\n");
	DispMat(g);
	G = (ALGraph *)malloc(sizeof(ALGraph));
	printf("转化成邻接表表示的图G;\n");
	MatToList(g,G);
	DispAdj(G);	
	printf("再转化成邻接矩阵表示的图g1:\n");
	g1=ListToMat(G,g1);
	DispMat(g1);
	printf("\n");
}

输出结果:
































































































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值