基础知识链接
邻接表详解
代码
#include <stdio.h>
#define max 100
struct ArcNode
{
int node;
struct ArcNode* next;
};
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);
struct ArcNode* h2 = malloc(sizeof(struct ArcNode*));
h2->node = head2;
h2->next = map->list[head1 - 1].first;
map->list[head1 - 1].first = h2;
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;
}
测试结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/6658cd589b094d24ac9151d92d803b87.png)