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; } } }改为头节点不存放数据
时间: 2024-02-10 10:09:11 浏览: 85
学生信息管理系统c++.zip
可以将头节点设置为空节点,不存放数据,如下所示:
```
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; // 将最后一个节点的 next 指针设为空
current = head; // 重置 current 指针
head = head->next; // 将头节点指向第一个有效节点
delete current; // 释放空节点的内存
}
```
这样头节点就不存放数据了,而是一个空节点,可以方便地进行链表操作。注意在函数结束前要释放空节点的内存。
阅读全文