以学生信息为例,写一篇动态链表,实现学生信息的插入,删除,查找,和输出,以及free
时间: 2024-05-01 21:23:58 浏览: 8
动态链表是一种数据结构,可以动态地管理数据,适用于需要频繁增删改查操作的场景。下面以学生信息为例,介绍如何实现动态链表。
首先,定义一个学生信息的数据结构,包括姓名、学号、年龄等信息:
```c
typedef struct student {
char name[20];
char id[10];
int age;
struct student *next;
} Student;
```
其中,`next` 指向下一个节点,形成链表。
接着,定义一些基本操作函数:
1. 创建一个空链表
```c
Student *create_list() {
Student *head = (Student*)malloc(sizeof(Student));
head->next = NULL;
return head;
}
```
2. 插入一个节点
```c
void insert_node(Student *head, Student *node) {
node->next = head->next;
head->next = node;
}
```
3. 查找一个节点
```c
Student *find_node(Student *head, char *id) {
Student *p = head->next;
while (p != NULL) {
if (strcmp(p->id, id) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
```
4. 删除一个节点
```c
void delete_node(Student *head, char *id) {
Student *p = head->next;
Student *pre = head;
while (p != NULL) {
if (strcmp(p->id, id) == 0) {
pre->next = p->next;
free(p);
return;
}
pre = p;
p = p->next;
}
}
```
5. 输出链表中所有节点
```c
void print_list(Student *head) {
Student *p = head->next;
while (p != NULL) {
printf("name: %s, id: %s, age: %d\n", p->name, p->id, p->age);
p = p->next;
}
}
```
最后,定义一个释放链表空间的函数:
```c
void free_list(Student *head) {
Student *p = head->next;
while (p != NULL) {
Student *temp = p;
p = p->next;
free(temp);
}
free(head);
}
```
使用以上函数,可以轻松地实现动态链表的插入、删除、查找和输出。例如:
```c
int main() {
Student *head = create_list();
Student *st1 = (Student*)malloc(sizeof(Student));
strcpy(st1->name, "Tom");
strcpy(st1->id, "001");
st1->age = 18;
insert_node(head, st1);
// 插入一个节点
Student *st2 = (Student*)malloc(sizeof(Student));
strcpy(st2->name, "Jack");
strcpy(st2->id, "002");
st2->age = 19;
insert_node(head, st2);
// 插入另一个节点
Student *st3 = find_node(head, "001");
printf("name: %s, id: %s, age: %d\n", st3->name, st3->id, st3->age);
// 查找节点
delete_node(head, "002");
// 删除节点
print_list(head);
// 输出所有节点
free_list(head);
// 释放空间
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)