标签:|| 需要 创建 span class list type getchar new
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4
5 struct student {
6 char id;
7 struct student* next;
8 };
9 typedef struct student S;
10 //创建节点
11 S* make_node(char id)
12 {
13 S* p = (S*)malloc(sizeof(S));//分配内存
14 if (NULL == p)
15 {
16 printf("fail to malloc\n");
17 return NULL;
18 }
19 memset(p, 0, sizeof(S));//结构体未初始化时数据是脏的,需要清一下
20 p->id = id;
21 p->next = NULL;
22 }
23
24 //头插节点
25 void top_add(S* ph, S* new)
26 {
27 S* a = ph;
28 new->next = ph->next;
29 ph->next = new;
30 }
31
32 //尾插节点
33 void tail_add(S* ph, S* new)
34 {
35 S* a = ph;
36 while (NULL != a->next)
37 {
38 a = a->next;
39 }
40 //跳出以上循环时,已经到了NULL的这个位置
41 a->next = new;
42 }
43
44 //打印链表
45 void print_list(S* ph)
46 {
47 while (NULL != ph->next)
48 {
49 ph = ph->next;
50 printf("%c\n", ph->id);
51 }
52 }
53
54 //删除数据对应的节点
55 int delete_node(S* ph,char letter)
56 {
57 S* a = ph;
58 S* prev = NULL;
59 while (NULL != a->next)
60 {
61 prev = a;
62 a = a->next;
63 if (a->id == letter)
64 {
65 prev->next = a->next;
66 return 0;
67 }
68 }
69 printf("没有要删除的节点\n");
70 return -1;
71 }
72
73 //反转链表
74 void node_inversion(S* ph)
75 {
76 S* a = ph->next;
77 S* aBack = NULL;
78 if (NULL == a || NULL == a->next)
79 {
80 return ;
81 }
82 while (NULL != a->next)
83 {
84 aBack = a->next;//保存第一个有效节点的下一个节点
85 if (a == ph->next)//第一个有效节点,即头指针的下一个节点,应指向NULL
86 {
87 a->next = NULL;
88 }
89 else
90 {
91 a->next = ph->next;//尾部链接
92 }
93 ph->next = a;//头部链接
94 a = aBack;//保留下一个节点
95 }
96 top_add(ph, a);//把最后一个节点插在头指针后面
97 }
98
99 int main()
100 {
101 char id = NULL;
102 S* header = make_node(NULL);
103
104 int N = 0;
105 printf_s("How many ids do you want?\n");
106 scanf_s("%d", &N);
107 getchar();
108 for (int i = 0; i < N; i++)//创建出N个节点并实现尾插
109 {
110 printf("<%d>", i + 1);
111 scanf_s("%c", &id);
112 getchar();
113 tail_add(header, make_node(id));
114 }
115 printf("list:\n");
116 print_list(header);
117
118 printf("Do you want to delete node? [1--yes;0--no]\n");
119 int r;
120 scanf("%d", &r);
121 getchar();
122 while (r)
123 {
124 printf("Which id will you delete?\n");
125 int ch;
126 scanf("%c", &ch);
127 delete_node(header,ch);
128 printf("Do you want to delete node? [1--yes;0--no]\n");
129 scanf("%d", &r);
130 getchar();
131 }
132 printf("list:\n");
133 print_list(header);
134
135 node_inversion(header);
136 printf("list after inversion:\n");
137 print_list(header);
138
139 free(header);
140 return 0;
141 }
测试结果如下:
标签:|| 需要 创建 span class list type getchar new
原文地址:https://www.cnblogs.com/Knight02/p/14331880.html