利用线性链表实现学生通信录管理系统
时间: 2023-07-11 16:07:21 浏览: 70
学生通信录管理系统可以通过使用线性链表来实现。下面是一些基本操作:
1. 定义结构体
首先,我们需要定义一个结构体表示学生通信录中的每个记录,包括学生姓名、学号、联系电话等信息。
```c
typedef struct student {
char name[20];
char id[10];
char phone[20];
struct student *next;
} Student;
```
2. 创建链表
然后,我们可以创建一个头指针指向链表的头节点,用于存储所有学生的信息。
```c
Student *head = NULL;
```
3. 插入节点
当用户需要添加新的学生信息时,我们可以通过以下代码将信息插入到链表中。
```c
void insert(Student **head_ref, char name[], char id[], char phone[]) {
// 创建新节点
Student *new_node = (Student*)malloc(sizeof(Student));
strcpy(new_node->name, name);
strcpy(new_node->id, id);
strcpy(new_node->phone, phone);
new_node->next = NULL;
// 如果链表为空,则将新节点作为头节点
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
// 找到链表的最后一个节点并将新节点插入到末尾
Student *last_node = *head_ref;
while (last_node->next != NULL) {
last_node = last_node->next;
}
last_node->next = new_node;
}
```
4. 删除节点
如果用户需要删除某个学生信息,我们可以通过以下代码从链表中删除该节点。
```c
void delete_student(Student **head_ref, char id[]) {
// 如果链表为空,直接返回
if (*head_ref == NULL) {
return;
}
// 如果第一个节点就是要删除的节点
if (strcmp((*head_ref)->id, id) == 0) {
Student *temp = *head_ref;
*head_ref = (*head_ref)->next;
free(temp);
return;
}
// 在链表中查找要删除的节点并删除
Student *prev_node = *head_ref;
Student *cur_node = prev_node->next;
while (cur_node != NULL && strcmp(cur_node->id, id) != 0) {
prev_node = cur_node;
cur_node = cur_node->next;
}
if (cur_node != NULL) {
prev_node->next = cur_node->next;
free(cur_node);
}
}
```
5. 修改节点
如果用户需要修改某个学生的信息,我们可以通过以下代码找到该节点并修改其信息。
```c
void modify_student(Student *head, char id[], char new_phone[]) {
// 在链表中查找要修改的节点并修改
Student *cur_node = head;
while (cur_node != NULL && strcmp(cur_node->id, id) != 0) {
cur_node = cur_node->next;
}
if (cur_node != NULL) {
strcpy(cur_node->phone, new_phone);
}
}
```
6. 查找节点
最后,如果用户需要查找某个学生的信息,我们可以通过以下代码在链表中查找该节点。
```c
void search_student(Student *head, char id[]) {
// 在链表中查找要查找的节点并输出其信息
Student *cur_node = head;
while (cur_node != NULL && strcmp(cur_node->id, id) != 0) {
cur_node = cur_node->next;
}
if (cur_node != NULL) {
printf("Name: %s\n", cur_node->name);
printf("ID: %s\n", cur_node->id);
printf("Phone: %s\n", cur_node->phone);
} else {
printf("Student not found.\n");
}
}
```
这样,我们就可以利用线性链表实现学生通信录管理系统了。