邻接表实现无向图存储

基础知识链接

邻接表详解

代码

#include <stdio.h>
#define max 100
//存储无向图
 struct ArcNode  //边
{
	int node; //指向的节点
	struct ArcNode* next;  //下一条弧指针
   // int val //可以加权值
};
typedef struct headList  //顶点
{
	char head; //顶点信息,可根据需要定义
	struct ArcNode* first;  //第一条弧
}headList;
typedef struct ALGraph
{
	headList list[max];  //顶点表
	int headnum, arcnum;  //边数,弧数
}ALGraph;
void CreatMap(ALGraph* map)
{
	printf("请输入顶点数和边数");
	scanf_s("%d%d", &map->headnum, &map->arcnum);  //顶点数,边数
	printf("请输入顶点字符,回车分割:");
	for (int i = 0; i < map->headnum; i++)  //初始化
	{
		getchar();  //将缓冲区回车读出
		scanf_s("%c", &map->list[i].head);
		map->list[i].first = NULL;
	}
	for (int j = 0; j < map->arcnum; j++)
	{
		printf("请输入构建边的两个顶点");
		//头插法构建,不推荐尾插法
		int head1, head2;
		scanf_s("%d%d", &head1, &head2);
		//head1
		struct ArcNode* h2 = malloc(sizeof(struct ArcNode*));
		h2->node = head2;
		h2->next = map->list[head1 - 1].first;
		map->list[head1 - 1].first = h2;
		//head2
		struct ArcNode* h1 = malloc(sizeof(struct ArcNode*));
		h1->node = head1;
		h1->next = map->list[head2 - 1].first;
		map->list[head2 - 1].first = h1;
	}
	return;
}
void Print(ALGraph map)
{
	for (int i = 0; i < map.headnum; i++)
	{
		printf("%c", map.list[i].head);
		struct ArcNode* s = map.list[i].first;
		while (s != NULL)
		{
			printf("%d", s->node);
			s = s->next;
		}
		printf("\n");
	}
}
int main()
{
	ALGraph map;
	CreatMap(&map);
	Print(map);
	return 0;
}

测试结果

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值