#include<stdio.h>
#include<malloc.h>
#define VERTEX_MAX 20
#define NULL 0
#define LEN sizeof(struct edgeNode)
struct edgeNode
{
int Vertex; //顶点信息
int weight; //权值
struct edgeNode *next; //指向下一个顶点坐标
};
struct ListGraph
{
edgeNode* AdjList[VERTEX_MAX]; //指向每个顶点的指针
int VextexNum;
int EdgeNum; //图的顶点的数量和边的数量
int GraphType; //图的结构
};
void CreateGraph(ListGraph *G)
{
int i,weight;
int start,end;
edgeNode *s;
for(i=1;i<=G->VextexNum;i++) //将图中各顶点指针清空
{
G->AdjList[i]=NULL;
}
for(i=1;i<=G->EdgeNum;i++) //输入各边的两个顶点
{
printf("第%d条边:",i);
scanf("%d,%d,%d",&start,&end,&weight);
//输入边的信息,起点,终点,权
s=(struct edgeNode *)malloc(LEN);
s->next=G->AdjList[start]; //插入到邻接表中
s->Vertex=end; //保存终点编号
s->weight=weight; //保存权值
G->AdjList[start]=s; //邻接表对应顶点指向该点
if(G->GraphType==0) //若是无向图则再插入到终点的边链中
{
s=(struct edgeNode *)malloc(LEN);
s->next=G->AdjList[end];
s->Vertex=start;
s->weight=weight;
G->AdjList[end]=s;
}
}
}
void OutList(ListGraph *G)
{
int i;
edgeNode *s;
for(i=1;i<=G->VextexNum;i++)
{
printf("顶点%d",i);
s=G->AdjList[i];
while(s)
{
printf("->%d(%d)",s->Vertex,s->weight);
s=s->next;
}
printf("\n");
}
}
void main()
{
ListGraph G;
printf("输入生成图的类型(0,有向图1,无向图):");
scanf("%d",&G.GraphType); //由用户选择图的种类
printf("输入图的顶点数量和边数量:");
scanf("%d,%d",&G.VextexNum,&G.EdgeNum);
//输入图的顶点数和边数
printf("输入构成各边的两个顶点及权值(用逗号隔开):\n");
CreateGraph(&G);
printf("输出图的邻接表:\n");
OutList(&G);
}
图-----邻接表
最新推荐文章于 2022-08-24 09:01:51 发布