假设我们要实现一个简单的学生信息管理系统,使用单链表来存储学生的信息。
定义学生信息结构体
首先,我们定义一个学生信息的结构体,包括学生的姓名和年龄,以及指向下一个学生的指针。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Student {
char name[50];
int age;
struct Student* next;
} Student;
创建新学生节点
接下来,我们定义一个函数来创建一个新的学生节点。
Student* createStudent(const char* name, int age) {
Student* newStudent = (Student*)malloc(sizeof(Student));
if (newStudent == NULL) {
printf("内存分配失败\n");
exit(1);
}
strcpy(newStudent->name, name);
newStudent->age = age;
newStudent->next = NULL;
return newStudent;
}
插入学生到链表
然后,我们定义一个函数来将新学生插入到链表的末尾。
void insertStudent(Student** head, const char* name, int age) {
Student* newStudent = createStudent(name, age);
if (*head == NULL) {
*head = newStudent;
} else {
Student* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newStudent;
}
}
打印链表
定义一个函数来遍历链表并打印每个学生的信息。
void printStudents(const Student* head) {
const Student* current = head;
while (current != NULL) {
printf("姓名: %s, 年龄: %d\n", current->name, current->age);
current = current->next;
}
}
删除学生
定义一个函数来删除链表中的一个学生节点。
void deleteStudent(Student** head, const char* name) {
Student* current = *head;
Student* previous = NULL;
while (current != NULL) {
if (strcmp(current->name, name) == 0) {
if (previous == NULL) {
*head = current->next; // 删除的是头节点
} else {
previous->next = current->next; // 删除的是中间的节点
}
free(current);
return;
}
previous = current;
current = current->next;
}
printf("未找到学生: %s\n", name);
}
主函数
最后,我们在主函数中使用这些函数。
int main() {
Student* head = NULL;
insertStudent(&head, "Alice", 20);
insertStudent(&head, "Bob", 22);
insertStudent(&head, "Charlie", 23);
printf("学生列表:\n");
printStudents(head);
deleteStudent(&head, "Bob");
printf("删除后的学生列表:\n");
printStudents(head);
// 释放链表内存
while (head != NULL) {
Student* temp = head;
head = head->next;
free(temp);
}
return 0;
}
这个例子展示了如何使用单链表来管理学生信息,包括创建节点、插入节点、打印链表、删除节点和释放链表内存。在实际应用中,链表可以用于更复杂的数据结构和算法,但基本原理是相似的。