学生链表的基本操作用c++怎么写
时间: 2024-06-10 16:10:39 浏览: 9
以下是学生链表的基本操作示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 20
struct student {
char name[MAX_NAME_LENGTH];
int age;
struct student *next;
};
typedef struct student Student;
// 添加学生
void add_student(Student **head, char *name, int age) {
Student *new_student = (Student*) malloc(sizeof(Student));
strcpy(new_student->name, name);
new_student->age = age;
new_student->next = NULL;
if (*head == NULL) {
*head = new_student;
} else {
Student *current_student = *head;
while (current_student->next != NULL) {
current_student = current_student->next;
}
current_student->next = new_student;
}
}
// 删除学生
void delete_student(Student **head, char *name) {
if (*head == NULL) {
return;
}
if (strcmp((*head)->name, name) == 0) {
Student *temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Student *current_student = *head;
while (current_student->next != NULL && strcmp(current_student->next->name, name) != 0) {
current_student = current_student->next;
}
if (current_student->next != NULL) {
Student *temp = current_student->next;
current_student->next = temp->next;
free(temp);
}
}
// 修改学生信息
void modify_student(Student *head, char *name, int age) {
Student *current_student = head;
while (current_student != NULL) {
if (strcmp(current_student->name, name) == 0) {
current_student->age = age;
return;
}
current_student = current_student->next;
}
}
// 查找学生
Student* find_student(Student *head, char *name) {
Student *current_student = head;
while (current_student != NULL) {
if (strcmp(current_student->name, name) == 0) {
return current_student;
}
current_student = current_student->next;
}
return NULL;
}
// 显示所有学生信息
void show_students(Student *head) {
Student *current_student = head;
while (current_student != NULL) {
printf("Name: %s, Age: %d\n", current_student->name, current_student->age);
current_student = current_student->next;
}
}
int main() {
Student *head = NULL;
add_student(&head, "Alice", 18);
add_student(&head, "Bob", 20);
add_student(&head, "Charlie", 19);
show_students(head);
printf("\n");
delete_student(&head, "Bob");
modify_student(head, "Charlie", 21);
show_students(head);
printf("\n");
Student *search_result = find_student(head, "Alice");
if (search_result != NULL) {
printf("Found student: %s, Age: %d\n", search_result->name, search_result->age);
} else {
printf("Student not found\n");
}
return 0;
}
```
该示例代码实现了学生链表的四个基本操作:添加学生、删除学生、修改学生信息和查找学生,并提供了一个显示所有学生信息的函数。其中,学生结构体包括姓名和年龄两个属性,添加学生和修改学生信息的函数都需要传入姓名和年龄,删除学生和查找学生的函数都需要传入姓名作为参数。在主函数中,首先添加了三个学生,然后显示所有学生信息;接着删除了一个学生和修改了另一个学生的年龄,再次显示所有学生信息;最后查找了一个学生并输出结果。