C语言——单链表的增删改查
程序员文章站
2022-05-08 14:44:03
...
我们需要先定义一下链表的结构
#ifndef LIST_H
#define LIST_H
#define L 50
//引入头文件
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<stdlib.h>
//定义链表数据域的数据结构体
typedef struct message {
char name[20];
int age;
} Item;
//定义链表
typedef struct node {
Item item;
struct node * next;
} Node, *List;
List creat(void);
bool add(List head);
bool del(List head);
bool change(List head);
bool search(List head);
void traverse(List head);
#endif
在这个基础上,我们实现以下相关的函数,我们先初始化一下链表。操作如下,先为链表创建一个头节点,为该节点分配内存,但不存放数据
List creat(void)
{
List head = (List)malloc(sizeof(Node));
//将头节点的下一个节点设置为NULL
head->next = NULL;
return head;
}
此时初始化完成,下面我们再实现一下增删改查的功能
bool add(List head)
{
//输入新结点的数据
Item people;
printf("Please input your name:");
gets(people.name);
printf("Please input your age:");
scanf("%d", &people.age);
//清空缓冲区
getchar();
//使用头插法插入数据
List p = (List)malloc(sizeof(Node));
p->item = people;
p->next = head->next;
head->next = p;
return true;
}
bool del(List head)
{
char nameWillBeenDelete[L];
printf("Please input the student's name who will you delete:");
gets(nameWillBeenDelete);
List prev = head;
List p = prev->next;
//查找数据,如果查询到,则在成功删除后return true
while (NULL != p) {
if (!strcmp(p->item.name, nameWillBeenDelete)) {
List t = p;
prev->next = p->next;
printf("%s has been delete!\n", t->item.name);
free(t);
return true;
}
prev = p;
p = p->next;
}
//如果查询完所有数据都没有找到,则return false
puts("Not found!");
return false;
}
//修改数据,与删除类似
bool change(List head)
{
char nameWillBeenChange[L];
printf("Please input the student's name who will you change:");
gets(nameWillBeenChange);
List p = head->next;
while (NULL != p) {
if (!strcmp(p->item.name, nameWillBeenChange)) {
printf("Please input your new name:");
gets(p->item.name);
printf("Please input your new age:");
scanf("%d", &p->item.age);
getchar();
printf("New:name:%s age:%d\n", p->item.name, p->item.age);
return true;
}
p = p->next;
}
puts("Not found!");
return false;
}
//查询
bool search(List head)
{
char nameWillBeenSearch[L];
printf("Please input the student's name who will you search:");
gets(nameWillBeenSearch);
List p = head->next;
while (NULL != p) {
if (!strcmp(p->item.name, nameWillBeenSearch)) {
printf("message: name:%s age:%d\n", p->item.name, p->item.age);
return true;
}
p = p->next;
}
printf("Not Found!\n");
return false;
}
我们已经定义好了链表的结构,并且也封装号了相关的功能,因此,我们只需要在main()函数中调用即可
#include"list.h"
int main(void)
{
//创建一个链表
List head = creat();
int n;
printf("Please input how number sutdents will you want:");
scanf("%d", &n);
getchar();
for (int i = 0; i < n; i++) {
add(head);
}
del(head);
change(head);
search(head);
traverse(head);
return 0;
}
下面是运行结果
GitHub源码地址
需要的可以自行下载
上一篇: 宿舍管理系统简单的增删改查