1.两种存储结构(邻接表和邻接矩阵)
#define INF 32767
#define MAXV 100
typedef char InfoType;
typedef struct
{ int no;
InfoType info;
} VertexType;
typedef struct
{ int edges[MAXV][MAXV];
int n,e;
VertexType vexs[MAXV];
} MatGraph;
typedef struct ANode
{ int adjvex;
struct ANode *nextarc;
int weight;
} ArcNode;
typedef struct Vnode
{ InfoType info;
int count;
ArcNode *firstarc;
} VNode;
typedef struct
{ VNode adjlist[MAXV];
int n,e;
} AdjGraph;
2.图的基本运算
#include
#include
#include "graph.h"
void CreateMat(MatGraph &g,int A[MAXV][MAXV],int n,int e)
{
int i,j;
g.n=n; g.e=e;
for (i=0;i<g.n;i++)
for (j=0;j<g.n;j++)
g.edges[i][j]=A[i][j];
}
void DispMat(MatGraph g)
{
int i,j;
for (i=0;i<g.n;i++)
{
for (j=0;j<g.n;j++)
if (g.edges[i][j]!=INF)
printf("%4d",g.edges[i][j]);
else
printf("%4s","∞");
printf("\n");
}
}
void CreateAdj(AdjGraph *&G,int A[MAXV][MAXV],int n,int e)
{
int i,j;
ArcNode *p;
G=(AdjGraph *)malloc(sizeof(AdjGraph));
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 (A[i][j]!=0 && A[i][j]!=INF)
{ p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=j;
p->weight=A[i][j];
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
G->n=n; G->e=n;
}
void DispAdj(AdjGraph *G)
{
int i;
ArcNode *p;
for (i=0;i<G->n;i++)
{
p=G->adjlist[i].firstarc;
printf("%3d: ",i);
while (p!=NULL)
{
printf("%3d[%d]→",p->adjvex,p->weight);
p=p->nextarc;
}
printf("∧\n");
}
}
void DestroyAdj(AdjGraph *&G)
{ int i;
ArcNode *pre,*p;
for (i=0;i<G->n;i++)
{ pre=G->adjlist[i].firstarc;
if (pre!=NULL)
{ p=pre->nextarc;
while (p!=NULL)
{ free(pre);
pre=p; p=p->nextarc;
}
free(pre);
}
}
free(G);
}
3.相互转换
#include "graph.cpp"
void MatToList(MatGraph g,AdjGraph *&G)
{ int i,j;
ArcNode *p;
G=(AdjGraph *)malloc(sizeof(AdjGraph));
for (i=0;i<g.n;i++)
G->adjlist[i].firstarc=NULL;
for (i=0;i<g.n;i++)
for (j=g.n-1;j>=0;j--)
if (g.edges[i][j]!=0 && g.edges[i][j]!=INF)
{ p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=j; p->weight= g.edges[i][j];
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
G->n=g.n;G->e=g.e;
}
void ListToMat(AdjGraph *G,MatGraph &g)
{ int i;
ArcNode *p;
for (i=0;i<G->n;i++)
{ p=G->adjlist[i].firstarc;
while (p!=NULL)
{ g.edges[i][p->adjvex]=p->weight;
p=p->nextarc;
}
}
g.n=G->n;g.e=G->e;
}
int main()
{
MatGraph g;
AdjGraph *G;
int A[MAXV][MAXV]={{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}};
int n=5, e=8;
CreateMat(g,A,n,e);
printf("图G的邻接矩阵:\n");
DispMat(g);
printf("将g转换为邻接表G\n");
MatToList(g,G);
printf("图G的邻接表:\n");
DispAdj(G);
DestroyAdj(G);
CreateAdj(G,A,n,e);
printf("图G的邻接表:\n");
DispAdj(G);
printf("将G转换为邻接矩阵g\n");
ListToMat(G,g);
DispMat(g);
DestroyAdj(G);
return 1;
}