用邻接表保存图

#include <stdio.h>
#include <stdlib.h>

#define VERTEX_MAX 20
#define  _CRT_SECURE_NO_WARNINGS
typedef struct edgeNode
{
	int Vertex;//顶点序号
	int weight;//权值
	struct edgeNode *next;//指向有边的下一个顶点
}EdgeNode;//邻接表边结构

typedef struct
{
	EdgeNode *AdjList[VERTEX_MAX];
	int VertexNum, EdgeNum;//图的顶点数量和边的数量
	int GraphType;//图的类型(0:无向图,1::有向图)

}ListGraph;

void CreateGraph(ListGraph *G);//生成图的邻接表
void OutList(ListGraph *G);//输出邻接表
/************************************************************************   
函数名称:main   
函数功能:测试图 
函数参数:无 
函数返回:0表示成功 
************************************************************************/  
int main()
{
	ListGraph G;
	printf("输入生成图的类型(0:无向图,1:有向图): ");
	scanf("%d", &G.GraphType);
	printf("输入的图的顶点数量和边数量:");
	scanf("%d,%d", &G.VertexNum, &G.EdgeNum);
	printf("输入构成各个边的两个顶点及权值(用逗号分隔):\n");
	CreateGraph(&G);
	printf("输出图的邻接表:\n");
	OutList(&G);

	getchar();
	getchar();
	return 0;
}
/************************************************************************   
函数名称:CreateGraph   
函数功能:构造邻接表结构图 
函数参数:G是定义的图结构的指针 
函数返回:无  
************************************************************************/  
void CreateGraph(ListGraph *G)
{
	int i, weight;
	int start, end;
	EdgeNode *s;
	for (i = 1; i <= G->VertexNum; i++)
		G->AdjList[i] = NULL;//将图中个顶点指针清空
	for (i = 1; i <= G->EdgeNum; i++)
	{
		getchar();
		printf("第%d条边:", i);
		scanf("%d,%d,%d", &start, &end, &weight);
		s = (EdgeNode *)malloc(sizeof(EdgeNode));
		s->next = G->AdjList[start];//插入到邻接表中
		s->Vertex = end;
		s->weight = weight;
		G->AdjList[start] = s;//邻接表对应顶点指向该点
		
		if (G->GraphType == 0)
		{
			s = (EdgeNode *)malloc(sizeof(EdgeNode));
			s->next = G->AdjList[end];//插入到邻接表中
			s->Vertex = start;
			s->weight = weight;
			G->AdjList[end] = s;//邻接表对应顶点指向该点
		}
	}

}

/************************************************************************   
函数名称:OutList   
函数功能:输出邻接表
函数参数:G是定义的图结构的指针 
函数返回:无  
************************************************************************/  
void OutList(ListGraph *G)
{
	int i;
	EdgeNode *s;
	for (i = 1; i <= G->VertexNum; i++)
	{
		printf("顶点%d", i);
		s = G->AdjList[i];
		while (s)
		{
			printf("->%d(%d)", s->Vertex, s->weight);
			s = s->next;
		}
		printf("\n");
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值