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; } void sortResults() { Athlete* i = head->next; if (i == NULL) return; else if (i->next == NULL) return; Athlete*current = head->next; i = i->next; while (i) { if (current->result <= i->result) { current = current->next; } else { Athlete* p1 = head; while (p1->next->result <= i->result) { p1 = p1->next; } current->next = i->next; i->next = p1->next; p1->next = i; } i = current->next; } }改成能够从文件每一个数据都参与排序
时间: 2024-02-10 17:09:11 浏览: 142
可以将loadFromFile()函数中的Athlete对象的创建放到while循环内部,并且将newAthlete的next指针初始化为head,这样每一次创建的Athlete对象都会插入到链表头部,即每个数据都会参与排序。修改后的代码如下:
```
void loadFromFile(const string& filename)
{
ifstream file(filename);
string line;
int number = 1;
head = new Athlete{ 0, 0, nullptr };
while (getline(file, line))
{
float result = stof(line);
Athlete* newAthlete = new Athlete{ number++, result, head };
head = newAthlete;
}
}
void sortResults()
{
Athlete* i = head->next;
if (i == NULL) return;
else if (i->next == NULL) return;
Athlete* current = head->next;
i = i->next;
while (i)
{
if (current->result <= i->result)
{
current = current->next;
}
else
{
Athlete* p1 = head;
while (p1->next->result <= i->result)
{
p1 = p1->next;
}
current->next = i->next;
i->next = p1->next;
p1->next = i;
}
i = current->next;
}
}
```
阅读全文