链表是一种常见的重要的数据结构,他是动态的进行存储分配的一种结构。

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h> //动态分配内存引入
#define NC sizeof(struct student) //宏定义内存大小
struct student //定义结构体数据类型
{
int num; //学号
int score; //分数
struct student *next; //下一个结点地址
};
int N; //全局变量,表示链表节点数
//函数声明
struct student *creat(void); //创建链表
void print(); //打印函数
struct student *del(); //删除函数
//主函数
int main()
{
struct student *stu, *p;
int num; //定义需删除的数据的num号

stu = creat(); //创建链表,返回头指针head
p = stu;
print(p); //打印数据
printf("Please input the num to delete:");
scanf("%d", &num);
print(del(p, num)); //调用del函数后,返回头指针,重新传递给print函数打印出数据
printf("\n\n");
system("pause"); //就是暂停程序的执行,等待任意健继续执行,查看结果,防止一闪而过
return 0;
}
//创建链表
struct student *creat(void)
{
struct student *p1, *p2, *head;
p1 = p2 = (struct student *)malloc(NC); //动态分配内存大小
printf("please input num :");
scanf("%d", &p1->num);
printf("please input score :");
scanf("%d", &p1->score);
head = NULL; //初始化
N = 0;
while (p1->num) {
N++;
if (N == 1) {
head = p1;
} else {
p2->next = p1;
}
p2 = p1;
p1 = (struct student *)malloc(NC);
printf("\nplease input num :");
scanf("%d", &p1->num);
printf("please input score :");
scanf("%d", &p1->score);
}
p2->next = NULL;
return head;
}
//输出链表
void print(struct student *head)
{
struct student *p;
printf("\nThere are %d records!\n", N);
p = head;
if (head) {
do {
printf("学号为%d的同学成绩是:%d\n", p->num, p->score);
p = p->next;
} while (p); // p为NULL时停止循环
}
}
//删除结点
struct student *del(struct student *head, int num) //形参
{
struct student *p1, *p2;
if (head == NULL) {
printf("\nThis is a NULL chart!");
goto END; //判断链表为空,直接跳转到返回语句
}
p1 = head; //不为空赋值给p1
while (p1->num != num && p1->next != NULL) {
p2 = p1;
p1 = p1->next;
}
if (num == p1->num) {
if (p1 == head) {
/* code */
head = p1->next;
} else {
p2->next = p1->next;
}
printf("\nDelete num:%d data success!", num);
N--;
} else {
printf("\nnum:%d not been found!", num);
}
END:
return head;
}