1.构造学生信息链表,学生信息应包括姓名和年龄(链表初始化) 2.根据自己的需要建立链表添加学生信息,学生信息不得少于3条(建立链表:头插法或者尾插法皆可) 3.打印出所有学生的信息(遍历),并统计学生人数(求链表长度) 4.在第二个位置插入一个学生信息,姓名为Tom,年龄为10(链表插入),并打印出插入后的学生信息表(遍历) 5.查找年龄为10的学生,打印其姓名(按值查找) 6.删除第二个学生的信息(删除),打印删除后的学生信息表(遍历)
时间: 2023-12-27 09:03:23 浏览: 76
学生信息建立采用链表结构
以下是C++代码实现:
```c++
#include <iostream>
using namespace std;
// 学生信息结构体
struct Student {
string name;
int age;
Student* next;
};
// 初始化链表
void initList(Student*& head) {
head = new Student;
head->next = NULL;
}
// 头插法添加学生信息
void addStudent(Student*& head, string name, int age) {
Student* newStudent = new Student;
newStudent->name = name;
newStudent->age = age;
newStudent->next = head->next;
head->next = newStudent;
}
// 打印所有学生信息
void printList(Student* head) {
Student* p = head->next;
int count = 0;
while (p) {
cout << "姓名:" << p->name << ",年龄:" << p->age << endl;
p = p->next;
count++;
}
cout << "总共有" << count << "个学生" << endl;
}
// 在第二个位置插入学生信息
void insertStudent(Student*& head, string name, int age) {
Student* p = head;
for (int i = 0; i < 2; i++) {
if (p->next == NULL) {
cout << "链表长度不足2" << endl;
return;
}
p = p->next;
}
Student* newStudent = new Student;
newStudent->name = name;
newStudent->age = age;
newStudent->next = p->next;
p->next = newStudent;
}
// 按值查找学生信息
void search(Student* head, int age) {
Student* p = head->next;
while (p) {
if (p->age == age) {
cout << "年龄为" << age << "的学生姓名为" << p->name << endl;
return;
}
p = p->next;
}
cout << "未找到年龄为" << age << "的学生" << endl;
}
// 删除第二个学生信息
void deleteStudent(Student*& head) {
Student* p = head;
for (int i = 0; i < 2; i++) {
if (p->next == NULL) {
cout << "链表长度不足2" << endl;
return;
}
p = p->next;
}
Student* temp = p->next;
p->next = temp->next;
delete temp;
}
int main() {
Student* head;
initList(head);
addStudent(head, "张三", 20);
addStudent(head, "李四", 19);
addStudent(head, "王五", 21);
printList(head);
insertStudent(head, "Tom", 10);
printList(head);
search(head, 10);
deleteStudent(head);
printList(head);
return 0;
}
```
阅读全文