1 //链表操作,涉及到链表首节点指针变动的函数,即使形参包含首节点指针,必须返回首节点指针,原因不得而知
2 # include<stdio.h>
3 # include<stdlib.h>
4 struct Student
5 {
6 int num;
7 struct Student* next;
8 };
9 struct Student* p;
10 int main()
11 {
12 struct Student*p1;
13 int n;
14 scanf("%d",&n);
15
16 int len(struct Student*);
17 struct Student* create(int); /*这里不能用void create(struct Student*,int);
18 因为创建链表涉及到链表首元素指针的变动,会出现错误,原因未解;*/
19
20 struct Student* insert(struct Student*,struct Student*,int); /*不能用void insert(struct Student*,struct Student*,int);
21 往链首插元素会涉及到链表首节点指针变动,从而引发错误*/
22
23
24 struct Student* del(struct Student*,int); /*不能用void del(struct Student*,int);
25 删除链首插元素会涉及到链表首节点指针变动,从而引发错误*/
26 void print(struct Student*);
27
28 p=create(n);
29 print(p);
30 p1=(struct Student*)malloc(sizeof(Student));
31 p1->num=15;
32
33 p=insert(p,p1,0);
34 print(p);
35 p=del(p,23);
36 print(p);
37
38 return 0;
39 }
40
41 int len(struct Student *p)
42 {
43 struct Student *p1=p;
44 int i=0;
45 while(p)
46 {
47 i++;
48 p=p->next;
49 }
50 return i;
51 }
52
53 struct Student* create(int n) /*这里不能用void create(struct Student*,int);
54 因为创建链表涉及到链表首元素指针的变动,会出现错误,原因未解;*/
55 {
56 int i=0;
57 struct Student*p1,*p2,*head;
58 p1=(struct Student*)malloc(sizeof(Student));
59 while(i<n)
60 {
61 i++;
62 p1->num=i;
63 if(i==1) head=p2=p1;
64 else
65 {
66 p2->next=p1;
67 p2=p1;
68 }
69 p1=(struct Student*)malloc(sizeof(Student));
70 }
71 free(p1);
72 p2->next=NULL;
73 p1=NULL;
74 return head;
75 }
76
77 struct Student* insert(struct Student* p,struct Student*p1,int n) /*不能用void insert(struct Student*,struct Student*,int);
78 往链首插元素会涉及到链表首节点指针变动,从而引发错误*/
79 {
80 struct Student*q;
81 q=p;
82 int i=1,j=len(p);
83 if(n<0||n>j)
84 {
85 printf("输入错误\n");
86 }
87 else if(n==0) //插到链头
88 {
89 p1->next=p;
90 p=p1;
91 }
92 else
93 {
94 for(;i<n;i++,q=q->next);
95 p1->next=q->next;
96 q->next=p1;
97 p1=NULL;
98 }
99 return p;
100 }
101
102 struct Student* del(struct Student* p,int n) /*不能用void del(struct Student*,int);
103 删除链首插元素会涉及到链表首节点指针变动,从而引发错误*/
104 {
105 struct Student*q,*r;
106 int i,j=len(p);
107
108 if(n<1||n>j)
109 {
110 printf("输入错误\n");
111 }
112
113 else if(n==1)
114 {
115 q=p;
116 p=p->next;
117 free(q);
118 }
119
120 else
121 {
122 r=p;
123 q=r->next;
124 for(i=2;i<n;i++,q=q->next,r=r->next);
125 r->next=q->next;
126 free(q);
127 }
128 return p;
129 }
130
131
132 void print(struct Student* p)
133 {
134 int i=0;
135 while(p!=NULL)
136 {
137 i++;
138 printf("%5d",p->num);
139 if(i%10==0) printf("\n");
140 p=p->next;
141 }
142 printf("\n");
143
144 }
运行结果:

来源:https://www.cnblogs.com/bboykaku/p/12530875.html