#include #include #include using namespace std;

// 城市结点的定义 struct CityNode { string cityName; // 城市名 double x; // x坐标 double y; // y坐标 CityNode* next; // 下一个结点指针 };

// 创建带头结点的单链表 CityNode* createLinkedList() { CityNode* head = new CityNode; head->next = nullptr; return head; }

// 插入城市信息 void insertCity(CityNode* head, string cityName, double x, double y) { CityNode* newNode = new CityNode; newNode->cityName = cityName; newNode->x = x; newNode->y = y; newNode->next = nullptr;

CityNode* p = head;
while (p->next != nullptr) {
    p = p->next;
}
p->next = newNode;

}

// 删除城市信息 void deleteCity(CityNode* head, double x, double y) { CityNode* p = head; while (p->next != nullptr) { if (p->next->x == x && p->next->y == y) { CityNode* temp = p->next; p->next = temp->next; delete temp; return; } p = p->next; } }

// 更新城市信息 void updateCity(CityNode* head, double x, double y, string newCityName) { CityNode* p = head->next; while (p != nullptr) { if (p->x == x && p->y == y) { p->cityName = newCityName; return; } p = p->next; } }

// 根据城市名返回位置坐标 void getCoordinateByName(CityNode* head, string cityName, double& x, double& y) { CityNode* p = head->next; while (p != nullptr) { if (p->cityName == cityName) { x = p->x; y = p->y; return; } p = p->next; } x = -1; y = -1; }

// 返回与给定位置坐标距离小于等于D的城市 void getCitiesByDistance(CityNode* head, double x, double y, double D, string& result) { CityNode* p = head->next; while (p != nullptr) { double distance = sqrt(pow(p->x - x, 2) + pow(p->y - y, 2)); if (distance <= D) { result += p->cityName + ' '; } p = p->next; } }

// 将链表中的数据存入文件 void saveToFile(CityNode* head, string filename) { ofstream outfile(filename); CityNode* p = head->next; while (p != nullptr) { outfile << p->cityName << ' ' << p->x << ' ' << p->y << endl; p = p->next; } outfile.close(); }

// 从文件中读取数据到链表中 void readFromFile(CityNode* head, string filename) { ifstream infile(filename); string cityName; double x, y; while (infile >> cityName >> x >> y) { insertCity(head, cityName, x, y); } infile.close(); }

int main() { CityNode* head = createLinkedList();

// 从文件中读取数据到链表中
readFromFile(head, 'city.txt');

// 插入城市信息
insertCity(head, 'Beijing', 39.9, 116.4);
insertCity(head, 'Shanghai', 31.2, 121.4);
insertCity(head, 'Guangzhou', 23.1, 113.2);

// 删除城市信息
deleteCity(head, 31.2, 121.4);

// 更新城市信息
updateCity(head, 39.9, 116.4, 'New Beijing');

// 根据城市名返回位置坐标
double x, y;
getCoordinateByName(head, 'New Beijing', x, y);
cout << 'New Beijing: ' << x << ', ' << y << endl;

// 返回与给定位置坐标距离小于等于D的城市
string result;
getCitiesByDistance(head, 23.1, 113.2, 100, result);
cout << 'Cities within 100 of (23.1, 113.2): ' << result << endl;

// 将链表中的数据存入文件
saveToFile(head, 'city.txt');

return 0;

}

C++ 单链表实现城市信息管理系统

原文地址: https://www.cveoy.top/t/topic/pcSh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录