用c语言单链表完成学生信息的增加 修改 删除 查询
时间: 2024-10-13 13:06:48 浏览: 22
基于c语言单链表的学生管理系统.zip
在C语言中,我们可以使用单链表结构来实现学生信息的增删改查操作。这里是一个简单的示例:
1. 定义结构体`Student`,包含学生的姓名(name)、学号(id)等属性:
```c
typedef struct {
char name[50];
int id;
struct Student* next; // 指向下一个学生的指针
} Student;
```
2. 创建链表头节点,并初始化为NULL:
```c
Student* head = NULL;
```
3. **增加(Insertion)**: 新建一个学生节点,然后将其添加到链表中适当的位置(例如按ID升序排序插入):
```c
void insert(Student* student) {
if (head == NULL) {
head = student;
} else {
Student* current = head;
while (current->id < student->id && current->next != NULL) {
current = current->next;
}
student->next = current->next;
current->next = student;
}
}
```
4. **修改(Modification)**: 找到指定的学生并更新其信息,如果找不到则返回错误信息:
```c
void update(int id, const char* new_name) {
Student* current = head;
while (current != NULL && current->id != id) {
current = current->next;
}
if (current != NULL) {
strncpy(current->name, new_name, sizeof(current->name));
} else {
printf("Student not found.\n");
}
}
```
5. **删除(Deletion)**: 查找并移除特定的学生节点(假设查找成功时只有一个匹配项):
```c
void delete(int id) {
if (head == NULL || head->id != id) return;
Student* temp = head;
head = head->next;
free(temp);
}
// 或者更通用的版本,遍历整个链表查找并处理
void safe_delete(Student** head, int id) {
if (*head == NULL || (*head)->id != id) return;
Student* to_remove = *head;
*head = (*head)->next;
free(to_remove);
}
```
6. **查询(Search)**: 根据学生ID查找并打印相关信息:
```c
void search(int id) {
Student* current = head;
while (current != NULL) {
if (current->id == id) {
printf("Name: %s, ID: %d\n", current->name, current->id);
break;
}
current = current->next;
}
}
```
阅读全文