每个学生包含姓名、性别、学号、成绩的输入,至少输入10个学生,并将成绩 按照男女分离形成两个单链表,并对两个单链表进行排序。
时间: 2024-03-10 09:51:26 浏览: 35
好的,这是一个比较典型的数据结构的应用题目,需要使用单链表和排序算法。以下是一个 C++ 的实现,仅供参考:
```C++
#include <iostream>
#include <string>
using namespace std;
// 学生信息结构体
struct Student {
string name;
string gender;
int id;
double score;
Student* next;
};
// 在链表末尾插入学生信息
void insertStudent(Student*& head, Student* student) {
if (head == nullptr) {
head = student;
} else {
Student* p = head;
while (p->next != nullptr) {
p = p->next;
}
p->next = student;
}
}
// 按照性别分离成两个链表
void splitByGender(Student* head, Student*& maleHead, Student*& femaleHead) {
Student* p = head;
while (p != nullptr) {
if (p->gender == "male") {
insertStudent(maleHead, new Student{*p});
} else {
insertStudent(femaleHead, new Student{*p});
}
p = p->next;
}
}
// 对链表进行冒泡排序
void bubbleSort(Student* head) {
bool swapped = true;
while (swapped) {
swapped = false;
Student* p = head;
while (p->next != nullptr) {
if (p->score > p->next->score) {
swap(p->score, p->next->score);
swapped = true;
}
p = p->next;
}
}
}
// 输出链表中的学生信息
void printStudents(Student* head) {
Student* p = head;
while (p != nullptr) {
cout << "Name: " << p->name << ", Gender: " << p->gender << ", ID: " << p->id << ", Score: " << p->score << endl;
p = p->next;
}
}
int main() {
// 输入学生信息
Student* head = nullptr;
for (int i = 0; i < 10; i++) {
Student* student = new Student;
cout << "Enter the information of student " << i + 1 << ":" << endl;
cout << "Name: ";
cin >> student->name;
cout << "Gender: ";
cin >> student->gender;
cout << "ID: ";
cin >> student->id;
cout << "Score: ";
cin >> student->score;
insertStudent(head, student);
}
// 分离男女链表并排序
Student* maleHead = nullptr;
Student* femaleHead = nullptr;
splitByGender(head, maleHead, femaleHead);
bubbleSort(maleHead);
bubbleSort(femaleHead);
// 输出结果
cout << "Male students:" << endl;
printStudents(maleHead);
cout << "Female students:" << endl;
printStudents(femaleHead);
// 释放内存
while (head != nullptr) {
Student* p = head;
head = head->next;
delete p;
}
while (maleHead != nullptr) {
Student* p = maleHead;
maleHead = maleHead->next;
delete p;
}
while (femaleHead != nullptr) {
Student* p = femaleHead;
femaleHead = femaleHead->next;
delete p;
}
return 0;
}
```
注意在实现中,需要使用一些指针操作来对链表进行操作,同时要注意内存管理,避免内存泄漏。
阅读全文