10 头插入法创建链表

 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 link* initLink() {
11     link* head = (link*)malloc(sizeof(link));
12     if (head) {
13         printf("创建头结点成功\n");
14         head->data = -1;
15         head->next = NULL;
16         return head;
17     }
18     else {
19         printf("创建头结点失败\n");
20         return;
21     }
22 }
23 
24 void insertFromHead(link*head_node,int num) {
25     link* new_node = (link*)malloc(sizeof(link)); //申请一个新节点
26     new_node->data = num; //新节点的值来源于接收的参数值
27     new_node->next = head_node; //新节点的指针域是定义的头结点
28     head_node= new_node; //头结点变为新节点
29     printf("头插入后链表头结点的值是:%d\n", head_node->data);
30 }
31 
32 void main() {
33     insertFromHead(initLink(), 3);
34     insertFromHead(initLink(), 4);
35 }

猜你喜欢

转载自www.cnblogs.com/shanlu0000/p/12457772.html