用c语言,不要用python
时间: 2023-08-10 17:43:31 浏览: 41
好的,以下是一个使用 C 语言编写的函数,可以让用户输入旅游路线图,并使用邻接表存储。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
struct node {
int val;
struct node* next;
};
void input_graph(struct node* graph[]) {
int num_vertices;
printf("请输入旅游路线图中的节点数:");
scanf("%d", &num_vertices);
for (int i = 0; i < num_vertices; i++) {
graph[i] = NULL; // 初始化邻接表为空
printf("请输入节点 %d 的邻接节点,以空格分隔,输入-1结束:\n", i);
while (1) {
int adj_node;
scanf("%d", &adj_node);
if (adj_node == -1) {
break;
}
// 创建新的邻接节点
struct node* new_node = (struct node*)malloc(sizeof(struct node));
if (new_node == NULL) {
printf("内存不足!");
exit(1);
}
new_node->val = adj_node;
new_node->next = NULL;
// 将邻接节点添加到邻接表中
if (graph[i] == NULL) {
graph[i] = new_node;
} else {
struct node* p = graph[i];
while (p->next != NULL) {
p = p->next;
}
p->next = new_node;
}
}
}
}
```
该函数首先让用户输入路线图中的节点数量,然后创建一个大小为 `num_vertices` 的邻接表数组。接下来,它对于每个节点,让用户输入它的邻接节点,直到用户输入-1表示邻接节点输入完成。对于每个邻接节点,函数会创建一个新的邻接节点,并将它添加到邻接表中。最后,邻接表数组会存储路线图的完整信息。