一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第八天,点击查看活动详情。
链表
接上篇,这里我们继续学习单向链表~(学习笔记)
对链表的删除操作
前言
从一个动态链表中删去一个结点,并不是真正的从内存中把它抹掉,而是把它从链表中分离开来,只要撤销原来的链表关系即可。
练习
题目:写一函数以删除动态链表中指定的结点。
思路:
- 从p指向的第一个结点开始,检查该结点中的num值是否等于输入的要求删除的那个学号。
- 如果相等就将该结点删除,如不相等,就将p后移一个结点,再如此进行下去,直到遇到表尾为止。
- 可以设两个指针变量p1和p2,先使p1指向第一个结点。
- 如果要删除的不是第一个结点,则使p1后移指向下一个结点(将p1->next赋给p1),在此之前将p1的值赋给p2,使p2指向刚才检查过的那个结点
综上我们可以得到以下流程图:
参考代码:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(struct student) //student结构的大小
struct student *create();//创建链表
struct student *del(struct student *head, int num);
void print(struct student *head);//打印链表
struct student {
int num;
float score;
struct student *next;
};
int n;//全局变量,用来记录存放了多少数据
int main() {
struct student *stu;
int n;
stu = create();
print(stu);
printf("Please enter the num to delete:");
scanf("%d", &n);
print(del(stu, n));
printf("\n\n");
system("pause");
}
struct student *create() {
struct student *head;
struct student *p1, *p2;
p1 = p2 = (struct student *)malloc(LEN);
head = NULL;
n = 0;
printf("Please enter the num:");
scanf("%d", &p1->num);
printf("Please enter the score:");
scanf("%f", &p1->score);
while (p1->num) {
n++;
if (1 == n) {
head = p1;
} else {
p2->next = p1;
}
p2 = p1;
p1 = (struct student *)malloc(LEN);
printf("\nPlease enter the num:");
scanf("%d", &p1->num);
printf("\nPlease enter the score:");
scanf("%f", &p1->score);
}
p2->next = NULL;
return head;
};
struct student *del(struct student *head, int num) {
struct student *p1, *p2;
p1 = head;
if (head == NULL) {
printf("\nThis list is null!\n");
goto END;
}
//这里p1是当前节点,p2是上一个节点。
//在单向链表中,需要用两个指针表示当前节点和上一个节点。
//在双向链表中,只需要一个指针就能实现功能。
while (p1->num != num && p1->next != NULL) {
p2 = p1; //更新p2
p1 = p1->next;
}
if (p1->num == num) {
if (p1 == head) {
head = p1->next;
} else {
p2->next = p1->next;
}
printf("Delete No:%d succeed!", num);
n = n - 1; //删除一个学号之后,全局变量n就要进行减一
} else {
printf("%d not been found!\n", num);
}
END:
return head;
};
void print(struct student *head) {
struct student *p;
p = head;
printf("\nThere are %d students' scores!\n", n);
if (head) {
do {
printf("学号为 %d 的学生的成绩为:%5.2f\n", p->num, p->score);
p = p->next;
} while (p);
}
}
声明
小编是跟着b站上的小甲鱼视频学习的,希望每天都能进步一点点!!
链接附上:C语言学习之小甲鱼视频链接