注:本程序邻接矩阵没有放进图结构体里
#include <stdio.h>
#include <stdlib.h>
#define MAXIMUM 100
typedef struct EdgeNode//弧(vi,vj)结点
{
int vertexnum;//弧尾序号j
struct EdgeNode *nextEdge;
}EdgeNode;
typedef struct VertexNode//顶点v结点
{
char vertex;//顶点v的信息
EdgeNode *FirstEdge;
}VertexNode[MAXIMUM];
typedef struct Graph
{
VertexNode adjList;//顶点数组集
int amountofvertex;//顶点数
int amountofedge;//弧数
}Graph;
void InitGraph(Graph *G)//图的创建
{
int i,j,k;
EdgeNode *p;
printf("请输入图的顶点数\n");
scanf("%d",&G->amountofvertex);
printf("请输入图的边数\n");
scanf("%d",&G->amountofedge);
printf("请按顺序插入顶点信息(以空格隔开)\n");
for(k=0;k<G->amountofvertex;k++)//插入顶点信息
{
getchar();
scanf("%c",&G->adjList[k].vertex);
G->adjList[k].FirstEdge=NULL; //初始化顶点结构体指针为空指针(指向NULL)
}
printf("请按顺序输入边的两个顶点下标(vi,vj)(i和j以空格隔开)\n");
printf("一行输入一条边\n");
for(k=0;k<G->amountofedge;k++)//插入顶点信息
{
getchar();
scanf("%d%d",&i,&j);
p=(EdgeNode *)malloc(sizeof(EdgeNode));
p->vertexnum=j; //储存弧尾(邻接点)下标
p->nextEdge=G->adjList[i].FirstEdge; //头插法
G->adjList[i].FirstEdge=p;
p=(EdgeNode *)malloc(sizeof(EdgeNode));
p->vertexnum=i; //储存弧头(邻接点)下标
p->nextEdge=G->adjList[j].FirstEdge; //头插法
G->adjList[j].FirstEdge=p;
}
printf("\n");
}
void printadjGraph(Graph *G)//输出邻接表
{
int i,j,k;
EdgeNode *p;
printf("邻接表:\n");
for(k=0;k<G->amountofvertex;k++)
{
for(p=G->adjList[k].FirstEdge;p;p=p->nextEdge)
printf("(%c,%c)",G->adjList[k].vertex,G->adjList[p->vertexnum].vertex);//打印边(如(A,B))
printf("\n");
}
printf("\n");
}
void printadjMatrix(Graph *G)//输出邻接矩阵
{
int adjMatrix[MAXIMUM][MAXIMUM]={0};
int i,j,k;
EdgeNode *p;
for(k=0;k<G->amountofvertex;k++)
{
for(p=G->adjList[k].FirstEdge;p;p=p->nextEdge)
adjMatrix[k][p->vertexnum]=1;//相连顶点赋值为1
}
printf("邻接矩阵:\n\n ");
for(i=0;i<G->amountofvertex;i++)//打印列头
printf("%3c",G->adjList[i].vertex);
printf("\n\n");
for(i=0;i<G->amountofvertex;i++)
{
printf("%2c|",G->adjList[i].vertex);//打印行头
for(j=0;j<G->amountofvertex;j++)
printf("%3d",adjMatrix[i][j]);//输出矩阵
printf("|");
printf("\n");
}
printf("\n");
}
int main(void)
{
Graph G;
InitGraph(&G);
printadjGraph(&G);
printadjMatrix(&G);
return 0;
}