输入若干行文本以“END!”结尾,根据输入文本生成邻接表,使用邻接表构成图来表达地铁线路C语言
时间: 2023-12-03 16:46:23 浏览: 31
以下是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STATION_NAME 50
typedef struct station Station;
struct station {
char name[MAX_STATION_NAME];
Station *next;
};
typedef struct {
Station *head;
} AdjList;
typedef struct {
int num_stations;
AdjList *adj_lists;
} Subway;
void add_station(AdjList *adj_list, char *name) {
Station *new_station = (Station*) malloc(sizeof(Station));
strcpy(new_station->name, name);
new_station->next = adj_list->head;
adj_list->head = new_station;
}
void add_connection(AdjList *adj_list, char *station1, char *station2) {
Station *station = adj_list->head;
while (station != NULL && strcmp(station->name, station1) != 0) {
station = station->next;
}
if (station == NULL) {
printf("Error: station %s does not exist\n", station1);
return;
}
add_station(adj_list, station2);
}
Subway *create_subway(int num_lines, char **lines) {
Subway *subway = (Subway*) malloc(sizeof(Subway));
subway->num_stations = 0;
subway->adj_lists = (AdjList*) malloc(num_lines * sizeof(AdjList));
for (int i = 0; i < num_lines; i++) {
subway->adj_lists[i].head = NULL;
char *line = lines[i];
char *station1 = strtok(line, ",");
char *station2 = strtok(NULL, ",");
while (station2 != NULL) {
add_connection(&subway->adj_lists[i], station1, station2);
add_connection(&subway->adj_lists[i], station2, station1);
subway->num_stations += 2;
station1 = station2;
station2 = strtok(NULL, ",");
}
}
return subway;
}
void print_subway(Subway *subway) {
printf("Subway:\n");
for (int i = 0; i < subway->num_stations; i++) {
printf("%d: ", i);
Station *station = subway->adj_lists[i / 2].head;
while (station != NULL && strcmp(station->name, subway->adj_lists[i / 2].head->name) != 0) {
station = station->next;
}
printf("%s\n", station->name);
}
}
void free_subway(Subway *subway) {
for (int i = 0; i < subway->num_stations; i++) {
Station *station = subway->adj_lists[i / 2].head;
while (station != NULL) {
Station *next_station = station->next;
free(station);
station = next_station;
}
}
free(subway->adj_lists);
free(subway);
}
int main() {
char *lines[] = {
"A1,A2,A3,A4,A5",
"B1,B2,B3,B4,B5",
"C1,C2,C3,C4,C5"
};
int num_lines = sizeof(lines) / sizeof(char*);
Subway *subway = create_subway(num_lines, lines);
print_subway(subway);
free_subway(subway);
return 0;
}
```
这个程序创建了一个简单的地铁系统,包含了三条线路 A、B 和 C,每条线路有 5 个站点。输入的文本格式如下:
```
A1,A2,A3,A4,A5
B1,B2,B3,B4,B5
C1,C2,C3,C4,C5
END!
```
程序将文本按逗号分隔,将每个站点添加到相应的邻接表中,然后将每对相邻站点之间的连接添加到邻接表中。最后,程序打印出整个地铁系统的邻接表。