c++生成一个学生信息链表,包括学号和姓名,学号由1,2,3,4,6排列并print输出,然后插入一个学号为5的学生信息到链表中,要求其排在4和6之间, 把排序后的结果print输出。
时间: 2024-02-04 09:04:10 浏览: 9
好的,以下是 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
class Student {
public:
int student_id;
string name;
Student* next;
Student(int id, string name) {
this->student_id = id;
this->name = name;
this->next = NULL;
}
};
int main() {
// 创建学生信息链表
Student* head = new Student(1, "Tom");
Student* tail = head;
tail->next = new Student(2, "Jack");
tail = tail->next;
tail->next = new Student(3, "Mary");
tail = tail->next;
tail->next = new Student(4, "Lucy");
tail = tail->next;
tail->next = new Student(6, "John");
tail = tail->next;
// 打印原始链表
Student* p = head;
while (p) {
cout << "学号: " << p->student_id << " 姓名: " << p->name << endl;
p = p->next;
}
// 插入学号为5的学生信息
p = head;
while (p->next) {
if (p->student_id == 4 && p->next->student_id == 6) {
Student* new_student = new Student(5, "Kate");
new_student->next = p->next;
p->next = new_student;
break;
}
p = p->next;
}
// 排序链表
Student* dummy = new Student(-1, "");
dummy->next = head;
tail = NULL;
while (tail != dummy->next) {
Student* cur = dummy->next;
Student* pre = dummy;
while (cur->next != tail) {
if (cur->student_id > cur->next->student_id) {
pre->next = cur->next;
cur->next = cur->next->next;
pre->next->next = cur;
cur = pre->next;
pre = dummy;
}
else {
cur = cur->next;
pre = pre->next;
}
}
tail = cur;
}
// 打印排序后的链表
p = dummy->next;
while (p) {
cout << "学号: " << p->student_id << " 姓名: " << p->name << endl;
p = p->next;
}
return 0;
}
```
输出结果为:
```
学号: 1 姓名: Tom
学号: 2 姓名: Jack
学号: 3 姓名: Mary
学号: 4 姓名: Lucy
学号: 6 姓名: John
学号: 1 姓名: Tom
学号: 2 姓名: Jack
学号: 3 姓名: Mary
学号: 4 姓名: Lucy
学号: 5 姓名: Kate
学号: 6 姓名: John
```