您的位置:首页 > 其它

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

2012-10-06 22:09 399 查看
第一次发文,还请各路大神指教。程序是对照《数据结构教程上机实验指导》写的,请指教。

辛苦排的版还是显示不出来,摸索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");
}

输出结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: