定义学生结构体struct Student类型如下: char id[10]; //学号 char Name[20];//姓名 double Score[3];//3门课程成绩 在主函数定义3个struct Student类型变量,并赋值,将3个变量插入到单链表的表头、表尾和指定位置
时间: 2024-01-20 09:04:03 浏览: 57
好的,以下是代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
struct Student {
char id[10];
char Name[20];
double Score[3];
Student* next;
};
// 在单链表表头插入节点
void InsertAtHead(Student* &head, Student* newStudent) {
newStudent->next = head;
head = newStudent;
}
// 在单链表表尾插入节点
void InsertAtTail(Student* &head, Student* newStudent) {
if (head == nullptr) {
head = newStudent;
} else {
Student* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newStudent;
}
}
// 在单链表指定位置插入节点
void InsertAtPos(Student* &head, Student* newStudent, int pos) {
if (pos <= 1) {
InsertAtHead(head, newStudent);
} else {
Student* temp = head;
int i = 1;
while (temp != nullptr && i < pos - 1) {
temp = temp->next;
i++;
}
if (temp == nullptr) {
cout << "指定位置不存在!" << endl;
} else {
newStudent->next = temp->next;
temp->next = newStudent;
}
}
}
int main() {
// 定义3个struct Student类型变量,并赋值
Student* student1 = new Student{"1001", "张三", {90, 80, 85}, nullptr};
Student* student2 = new Student{"1002", "李四", {95, 85, 90}, nullptr};
Student* student3 = new Student{"1003", "王五", {80, 75, 70}, nullptr};
// 将3个变量插入到单链表的表头、表尾和指定位置
Student* head = nullptr;
InsertAtHead(head, student1);
InsertAtTail(head, student2);
InsertAtPos(head, student3, 2);
// 遍历单链表并输出每个节点的信息
Student* temp = head;
while (temp != nullptr) {
cout << "学号:" << temp->id << ",姓名:" << temp->Name << ",成绩:";
for (int i = 0; i < 3; i++) {
cout << temp->Score[i] << " ";
}
cout << endl;
temp = temp->next;
}
return 0;
}
```
输出结果如下:
```
学号:1001,姓名:张三,成绩:90 80 85
学号:1003,姓名:王五,成绩:80 75 70
学号:1002,姓名:李四,成绩:95 85 90
```
阅读全文