使用链表实现学生的查询/添加/删除等操作的代码
时间: 2023-12-29 19:03:00 浏览: 24
以下是使用链表实现学生的查询/添加/删除等操作的C++代码示例:
```c++
#include <iostream>
using namespace std;
// 定义学生结构体
struct Student {
int id;
string name;
int age;
Student* next;
};
// 添加学生
Student* addStudent(Student* head, int id, string name, int age) {
Student* newStudent = new Student;
newStudent->id = id;
newStudent->name = name;
newStudent->age = age;
newStudent->next = NULL;
if (head == NULL) {
head = newStudent;
} else {
Student* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newStudent;
}
return head;
}
// 查询学生
void findStudent(Student* head, int id) {
Student* current = head;
while (current != NULL) {
if (current->id == id) {
cout << "ID: " << current->id << endl;
cout << "Name: " << current->name << endl;
cout << "Age: " << current->age << endl;
return;
}
current = current->next;
}
cout << "Student not found." << endl;
}
// 删除学生
Student* deleteStudent(Student* head, int id) {
if (head == NULL) {
return NULL;
}
if (head->id == id) {
Student* temp = head->next;
delete head;
return temp;
}
Student* current = head;
while (current->next != NULL && current->next->id != id) {
current = current->next;
}
if (current->next != NULL) {
Student* temp = current->next;
current->next = current->next->next;
delete temp;
}
return head;
}
// 打印学生信息
void printStudents(Student* head) {
Student* current = head;
while (current != NULL) {
cout << "ID: " << current->id << endl;
cout << "Name: " << current->name << endl;
cout << "Age: " << current->age << endl;
current = current->next;
}
}
int main() {
Student* head = NULL;
// 添加学生
head = addStudent(head, 1, "Tom", 18);
head = addStudent(head, 2, "Jack", 19);
head = addStudent(head, 3, "Lucy", 20);
// 查询学生
findStudent(head, 2);
// 删除学生
head = deleteStudent(head, 2);
// 打印学生信息
printStudents(head);
return 0;
}
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)