11 头插入法创建链表)

1,创建尾指针的方式,让尾指针不断往前移动

 1 /*头插入创建单链表*/
 2 
 3 #include<stdio.h>
 4 #include<stdlib.h>
 5 
 6 typedef struct Link {
 7     int data;
 8     struct Link* next;
 9 }link;
10 
11 
12 //头插入的方式初始化链表
13 link* initByHeadInsert() {
14     link* ptail =NULL; //创建尾指针
15 
16     //先初始话最后一个结点
17     link* last_node = (link*)malloc(sizeof(link));
18     last_node->data = 1;
19     last_node->next = NULL;
20     ptail = last_node;  //让尾指针指向最后一个结点
21 
22     //头插入赋值
23     for (int i = 2; i < 5; i++) {
24         link* new_node = (link*)malloc(sizeof(link)); //申请一个新节点
25         new_node->data = i; //给新节点赋初值
26         new_node->next = last_node; //新节点的指针域是最后一个结点
27         last_node=new_node; //新节点成为最后一个结点
28 
29         ptail = new_node; //尾指针指向这个新节点,不断往前移动
30 
31         //printf("尾指针指向的值是:%d
", ptail->data);//2 3 4
32         
33     }
34 
35     return ptail; //将指向最后一个结点的尾指针返回
36 }
37 
38 
39 //遍历链表
40 void showLink(link* ptail) {
41     link* tmp = ptail;
42     while (tmp!=NULL) {
43         printf("%d ", tmp->data);
44         tmp = tmp->next;
45     }
46 }
47 
48 void main() {
49     printf("头插入赋值的初始化链表为:
");
50     link* ptail = initByHeadInsert();; //创建尾指针,获取初始化后的尾指针
51     showLink(ptail);
52     
53 }

-----------------------------------------------------------------------------------------------------------------------------------------

头插入法(创建空结点的方式)

 1 /*头插入创建单链表(创建空节点的方式)*/
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 
 5 typedef struct Link {
 6     int data;
 7     struct Link* next;
 8 }link;
 9 
10 //全局定义尾结点
11 link* tail_node = NULL;
12 
13 //初始化链表(头结点)
14 void initLink() {
15     tail_node = (link*)malloc(sizeof(link));
16     tail_node->next = NULL;
17 }
18 
19 //头插入
20 link* HeadInsert(int num) {
21     initLink();
22     link* new_node = (link*)malloc(sizeof(link));
23     new_node->data = num;
24     new_node->next =tail_node;
25     tail_node = new_node; //尾结点向前移动
26     printf("%d ", tail_node->data);
27     return tail_node;
28 }
29 
30 //遍历打印
31 void showLink(link* tailNode) {
32     
33 }
34 
35 void main() {
36     printf("头插入一个数之后的链表是:
");
37     showLink(HeadInsert(3));
38     /*for (int i = 0; i < 5; i++) {
39         showLink(HeadInsert(i));
40     }*/
41     
42     
43 }

 但是,头插入的遍历打印 如何实现???

原文地址:https://www.cnblogs.com/shanlu0000/p/12459235.html