无向图的邻接矩阵转邻接表:
#include <stdio.h>
#include<stdlib.h>
#define MAXV 100
//以下定义邻接矩阵类型
typedef struct
{
int vexs[MAXV];
int arcs[MAXV][MAXV];
int vexnum,arcnum;
} MGraph;
//以下定义邻接表类型
typedef struct ANode
{
int adjvex;
struct ANode *nextarc;
} ArcNode;
typedef struct Vnode
{
int data;
ArcNode *firstarc;
} VNode;
typedef struct
{
VNode vertices[MAXV];
int vexnum,arcnum;
} ALGraph;
void MatToList(MGraph g,ALGraph *&G)
//将邻接矩阵g转换成邻接表G
{
int i,j;
ArcNode *p,*s;
G=(ALGraph *)malloc(sizeof(ALGraph));
for (i=0; i<g.vexnum; i++)
G->vertices[i].firstarc=NULL;
for (i=0; i<g.vexnum; i++)
for (j=0; j<g.vexnum; j++)
if (g.arcs[i][j]!=0)
{
p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=j; p->nextarc=NULL;
if(!G->vertices[i].firstarc)
G->vertices[i].firstarc=p;
else{
s=G->vertices[i].firstarc;
while(s->nextarc) s=s->nextarc;
s->nextarc=p;
}
}
G->vexnum=g.vexnum;
G->arcnum=g.arcnum;
}
void Output(ALGraph *G)
//输出邻接表G
{
int i;
ArcNode *p;
for (i=0; i<G->vexnum; i++)
{
p=G->vertices[i].firstarc;
printf("v%d:",i+1);
while (p!=NULL)
{
printf("%2d",p->adjvex);
p=p->nextarc;
}
printf("\n");
}
}
int main()
{
int i,j;
MGraph g;//定义图的邻接矩阵
ALGraph *G;//邻接表
int n,m;
printf("输入图G的邻接矩阵顶点数:\n");
scanf("%d",&n);
printf("输入图G的邻接矩阵边数:\n");
scanf("%d",&m);
int A[20][20];//邻接矩阵
printf("输入图G的邻接矩阵:\n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
scanf("%d",&A[i][j]);
}
}
g.vexnum=n;
for (i=0; i<g.vexnum; i++)
for (j=0; j<g.vexnum; j++)
g.arcs[i][j]=A[i][j];
printf("图G的邻接矩阵转换成邻接表:\n");
MatToList(g,G);
Output(G);
return 0;
}