1 //链表保存学生的基本信息 删除用户输入年龄和链表结点相同de
2
3 //2017.3.7
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #define _CRT_SECURE_NO_WARNINGS
9 typedef struct student su;
10 struct student
11 {
12 int age;
13 char name[100];
14 int number;
15 int sex;
16 struct student *next;
17 };
18
19 //初始化链表
20 su* init()
21 {
22 su *p = (su*)malloc(sizeof(su));//分配空间
23 if (NULL == p)
24 {
25 printf("分配失败\n");
26 }
27 else
28 {
29 p->next = NULL;
30 }
31 return p;//返回创建的头节点
32 }
33
34 //学生信息插入链表
35 su* insert(su *head, int num, int age, int sex,char *name)
36 {
37 su *p = head;//指向头
38 if (NULL == p)
39 {
40 return NULL;
41 }
42 while (p->next != NULL)
43 {
44 p = p->next;
45 }
46 su *pp = (su*)malloc(sizeof(su));
47 if (NULL == pp)
48 {
49 return NULL;
50 }else
51 {
52 pp->number = num;
53 strcpy_s(p->name, name);
54 pp->age = age;
55 pp->sex = sex;
56
57 p->next = pp;
58 pp->next = NULL;
59 }
60 }
61
62 void print(su *head)//传来头节点
63 {
64 su *p = head->next;
65 while (p != NULL)
66 {
67 printf("%5d", p->age);
68 p = p->next;
69 }
70 printf("\n");
71
72 }
73 void DeleteNode(su* pre, su *cur)
74 {
75 pre->next = cur->next; // 删除cur节点,pre是cur的前置节点
76 free(cur);
77 }
78 int main()
79 {
80 int num;
81 scanf_s("%d", &num); // 输入
82 su * c = init(); // 初始化链表,并插入一堆数据
83 insert(c, 1, 12, 1, "mike");
84 insert(c, 2, 13, 0, "jake");
85 insert(c, 3, 14, 1, "tom");
86 insert(c, 3, 14, 0, "xsan");
87 insert(c, 4, 15, 1, "lisi");
88 print(c);
89 printf("--------------------------------\n");
90 su * index = c->next;
91 su * flower = c;
92 while (index != NULL) // 遍历所有节点
93 {
94 if (index->age == num) // 如果节点的年纪是指定需要删除的年纪
95 {
96 DeleteNode(flower, index); // 删除该节点
97 index = flower->next; // 继续遍历
98 }
99 else
100 {
101 index = index->next; // 只是继续遍历
102 flower = flower->next;
103 }
104
105
106 }
107 print(c); // 输出新的链表
108 system("pause");
109 }
