有10个学生,每个学生的数据(struct studentrec)包括学号、姓名、三门课的成绩 从键盘输入10个学生的数据,组成学生数据双向链表,输入完后,从链表中删除三门成绩相同的节点,并重新组成新的双向链表。
时间: 2023-12-15 13:18:06 浏览: 65
以下是 C++ 代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
struct studentrec {
int id;
string name;
int score1, score2, score3;
studentrec *prev, *next;
};
void insertStudent(studentrec *&head, studentrec *&tail, studentrec *node) {
if (head == nullptr) {
head = tail = node;
} else {
tail->next = node;
node->prev = tail;
tail = node;
}
}
void deleteStudent(studentrec *&head, studentrec *&tail, studentrec *node) {
if (node == head) {
head = head->next;
if (head != nullptr) {
head->prev = nullptr;
}
} else if (node == tail) {
tail = tail->prev;
if (tail != nullptr) {
tail->next = nullptr;
}
} else {
node->prev->next = node->next;
node->next->prev = node->prev;
}
delete node;
}
int main() {
studentrec *head = nullptr, *tail = nullptr;
// 从键盘输入10个学生的数据
for (int i = 0; i < 10; i++) {
studentrec *node = new studentrec;
cout << "请输入第" << i+1 << "个学生的数据:" << endl;
cin >> node->id >> node->name >> node->score1 >> node->score2 >> node->score3;
node->prev = node->next = nullptr;
insertStudent(head, tail, node);
}
// 从链表中删除三门成绩相同的节点
for (studentrec *node = head; node != nullptr; node = node->next) {
if (node->next == nullptr) {
break;
}
if (node->score1 == node->next->score1 &&
node->score2 == node->next->score2 &&
node->score3 == node->next->score3) {
deleteStudent(head, tail, node->next);
}
}
// 输出新的双向链表
for (studentrec *node = head; node != nullptr; node = node->next) {
cout << "学号:" << node->id << ",姓名:" << node->name << ",成绩:" << node->score1 << " " << node->score2 << " " << node->score3 << endl;
}
// 释放链表内存
while (head != nullptr) {
studentrec *node = head;
head = head->next;
delete node;
}
return 0;
}
```
以上代码中,insertStudent() 函数用于将新的节点插入到链表的尾部,deleteStudent() 函数用于从链表中删除指定节点,main() 函数中先从键盘输入10个学生的数据,然后遍历链表,删除三门成绩相同的节点,最后输出新的链表。
阅读全文