void loadFromFile(const string& filename) { ifstream file(filename); string line; int number = 1; while (getline(file, line)) { float result = stof(line); Athlete* newAthlete = new Athlete{ number++, result, nullptr }; if (head == nullptr) { head = newAthlete; } else { Athlete* current = head; while (current->next != nullptr) { current = current->next; } current->next = newAthlete; } } }*/ void loadFromFile(const string& filename) { ifstream file(filename); string line; int number = 1; Athlete* current = new Athlete{ 0, 0, nullptr }; head = current; while (getline(file, line)) { float result = stof(line); Athlete* newAthlete = new Athlete{ number++, result, nullptr }; current->next = newAthlete; current = newAthlete; } current->next = nullptr; current = head; head = head->next; delete current; }改写成能读取文件所有数据并且排序,不用容器
时间: 2024-02-10 12:09:11 浏览: 154
以下是改写后的代码:
```
void loadFromFile(const string& filename) {
ifstream file(filename);
string line;
Athlete* current = new Athlete{ 0, 0, nullptr };
head = current;
while (getline(file, line)) {
float result = stof(line);
Athlete* newAthlete = new Athlete{ 0, result, nullptr };
current->next = newAthlete;
current = newAthlete;
}
current = head->next;
head->next = nullptr;
while (current != nullptr) {
Athlete* prev = head;
while (prev->next != nullptr && prev->next->result <= current->result) {
prev = prev->next;
}
current->next = prev->next;
prev->next = current;
current = current->next;
}
current = head;
head = head->next;
delete current;
}
```
这里使用了插入排序的方法对链表进行排序,不用容器。首先读取文件中的每个结果,构建链表。然后从第二个节点开始遍历链表,每次将当前节点插入到已经排序好的节点中。最后删除头节点并返回排序后的链表。注意,这里的 `Athlete` 结构体中的 `number` 字段是没有用的,因为排序只涉及到 `result` 字段。
阅读全文