数据结构之线性表-尾插法创建单链表-学习笔记-16

引入

我们学习了用头插法和尾插发创建一个单链表,今天我们在学习如何删除整个单链表。

删除整个单链表

其实就是再内存中将它释放掉,留出空间给其它软件使用。
整表删除思路:

  • 声明结点 p 和 q
  • 第一个结点给 p,第二个结点给 q
  • 释放完 p,将 q 指向的给 p
  • 释放完 q,将 p 指向的给 q
  • 循环执行,直到完全释放完毕

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct Student)
struct Student{
int num;
char name[20];
float score;
struct Student *next;
};

struct Student *create(void){
struct Student *a,*b,*head;
a=(struct Student *)malloc(LEN); //创建结点
head=(struct Student *)malloc(LEN);
b=head; //b 是指向尾部的节点
printf("请输入学生信息:\n");
scanf("%d %s %f",&a->num,a->name,&a->score);
while(a->num!=0){
b->next=a;
b=a;
a=(struct Student *)malloc(LEN);
scanf("%d %s %f",&a->num,a->name,&a->score);
}
b->next=NULL;
return head;
}

void print(struct Student * p){
p=p->next;
while(p!=NULL){
printf("%d号%s的成绩是:%3.1f\n",p->num,p->name,p->score);
p=p->next;
}
}

void delete_p(struct Student * p){
struct Student *a,*b;
a=p->next; //先让 a 指向第一个结点
while(a){
b=a->next; //b 记住 a 的下一个结点
free(a); //释放 a
a=b; //a 成为第下一个结点
}
p->next=NULL;
}

int main(){
struct Student* stu_p;
stu_p=create();
print(stu_p);
delete_p(stu_p);
print(stu_p);
return 0;
}

其实就是让 a 在中间过渡了一下。

伪代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <time.h>
#define ERROR 0
#define OK 1
typedef int Elemtype
struct Node{
Elemtype data;
struct Node * next;
};
//构建单链表
typedef struct Node* LinkList;

Status ClearList(LinkList *L){
LinkList *a,*b;
a=L->next;
while(a){
b=a->next;
free(a);
a=b;
}
L->next=NULL;
return OK;
}

非常简单~
一个先留着线索,另一个开始删,然后根据线索再找到下一个。

尾巴

这是我的个人学习笔记,主要是应付考研复习使用,充斥着一些吐槽和个人观点,并不严谨,欢迎大家参考、指正。


-------------The End-------------
欢迎请我喝咖啡哦~!