C语言编写:将若干城市的信息存人一个带头结点的单链表,结点中的城市信息包括城市名、城市的位置坐标,要求: (1)给定一个城市名,返回其位置坐标; (2)给定一个位置坐标P和一个距离D,返回所有与P的距离小于等于D的城市
时间: 2024-10-10 22:05:20 浏览: 31
在C语言中,你可以使用结构体来表示每个城市的节点,并定义一个链表结构来存储这些节点。首先,创建一个名为`City`的结构体,包含城市名和位置坐标:
```c
typedef struct {
char* city_name;
double position_x;
double position_y;
} City;
typedef struct Node {
City city_info;
struct Node* next;
} Node;
```
然后定义链表头指针并初始化它:
```c
Node* head = NULL;
```
对于(1),你需要遍历链表查找指定城市名的节点,找到后返回它的位置坐标:
```c
double find_position_by_name(char* name) {
Node* current = head;
while (current != NULL && strcmp(current->city_info.city_name, name) != 0) {
current = current->next;
}
if (current == NULL) {
printf("City not found.\n");
return -1; // 或者抛出错误,取决于你的处理方式
}
return current->city_info.position_x;
}
```
对于(2),同样遍历链表,计算每个城市到给定点P的距离并与给定的阈值比较:
```c
void find_cities_within_distance(double p_x, double p_y, double d) {
Node* current = head;
while (current != NULL) {
double distance = sqrt(pow(current->city_info.position_x - p_x, 2) + pow(current->city_info.position_y - p_y, 2));
if (distance <= d) {
printf("%s is within %f km from the point (%f, %f).\n", current->city_info.city_name, distance, p_x, p_y);
}
current = current->next;
}
}
```
阅读全文