(4) STU *Max(STU *head):查找总成绩最高的学生,返回指向该学生结点的指针
时间: 2024-04-11 20:33:23 浏览: 43
你可以使用以下代码来实现查找总成绩最高的学生并返回指向该学生节点的指针:
```cpp
#include <iostream>
struct STU {
std::string name;
int score;
STU* next;
};
STU* Max(STU* head) {
if (head == nullptr) {
return nullptr; // 如果链表为空,则返回空指针
}
STU* maxStudent = head;
STU* current = head->next;
while (current != nullptr) {
if (current->score > maxStudent->score) {
maxStudent = current;
}
current = current->next;
}
return maxStudent;
}
int main() {
// 创建链表并添加学生信息
STU* head = new STU{"Alice", 85, nullptr};
head->next = new STU{"Bob", 92, nullptr};
head->next->next = new STU{"Charlie", 78, nullptr};
head->next->next->next = new STU{"Dave", 95, nullptr};
// 调用 Max 函数查找总成绩最高的学生
STU* maxStudent = Max(head);
// 输出最高成绩学生的信息
std::cout << "最高成绩学生:" << maxStudent->name << ",成绩:" << maxStudent->score << std::endl;
// 释放链表内存
while (head != nullptr) {
STU* temp = head;
head = head->next;
delete temp;
}
return 0;
}
```
在这个例子中,我们使用了一个简单的链表数据结构来存储学生信息,包括姓名和成绩。`Max` 函数遍历链表,找到总成绩最高的学生,并返回指向该学生节点的指针。
注意:这只是一个简单的示例,实际应用中可能需要考虑更多的边界情况和错误处理。