自引用结构--之链表指定位置添加元素

代码:

 1 //This is c program code!                                                                       
 2 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
 3   * 文档信息: *** :~/testTmp3.c
 4   * 版权声明: *** :(魎魍魅魑)MIT
 5   * 联络信箱: *** :guochaoxxl@163.com
 6   * 创建时间: *** :2020年11月28日的上午10:18
 7   * 文档用途: *** :数据结构与算法分析-c语言描述
 8   * 作者信息: *** :guochaoxxl(http://cnblogs.com/guochaoxxl)
 9   * 修订时间: *** *2020年第47周 11月28日 星期六 下午02:57 (333天)
10   * 文件描述: *** :自行添加
11  * *+=+=+=+=* *** *+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+*/
12 #include <stdio.h>
13 #include <string.h>
14 #include <stdlib.h>
15 
16 typedef struct _stu{
17     char name[10];
18     struct _stu *next;
19 } Stu;
20 
21 int main(int argc, char **argv)
22 {
23     Stu *head;
24     Stu *tmp;
25     head = tmp = (Stu *)malloc(sizeof(Stu));
26     tmp->next = NULL;
27 
28     char *stuName[] = {"lina", "mina", "bina", "tina", "dina"};
29     int size = sizeof(stuName)/sizeof(stuName[0]);
30 
31     for(int i = 0; i < size; i++){
32         strcpy(tmp->name, stuName[i]);
33         Stu *tmpN = (Stu *)malloc(sizeof(Stu));
34         tmpN->next = NULL;
35         tmp->next = tmpN;
36         tmp = tmpN;
37     }
38 
39     printf("insert before: 
");
40     Stu *head1 = head;
41     for(int i = 0; i < size; i++){
42         printf("%s
", head1->name);
43         head1 = head1->next;
44     }
45 
46     printf("insert ‘pina’ after ‘bina’: 
");
47     Stu *head2 = head;
48     Stu *tmpP = head2;
49     
50     Stu *new = (Stu *)malloc(sizeof(Stu));
51     strcpy(new->name, "pina");
52     new->next = NULL;
53 
54     int flag = 1;
55     while(NULL != tmpP && flag){
56         if(strcmp(tmpP->name, "bina")){
57             tmpP = tmpP->next;
58         }else{
59             new->next = tmpP->next;
60             tmpP->next = new;
61             flag = 0;
62             size++;
63         }
64     }
65         
66     for(int i = 0; i < size; i++){
67         printf("%s
", head2->name);
68         head2 = head2->next;
69     }
70 
71     return 0;
72 }

运行结果:

insert before: 
lina
mina
bina
tina
dina
insert 'pina' after 'bina': 
lina
mina
bina
pina
tina
dina
原文地址:https://www.cnblogs.com/guochaoxxl/p/14053943.html