- Method 1:
- By
返回值
returning the requested one 头结点所在的内存空间首地址
, that is, creating the head node of the one-way linked list, the code is as follows:
- Sample code:
node_t *create_link_node_1(){
node_t *phead = (node_t *)malloc(sizeof(node_t));
if(NULL == phead){
printf("内存分配失败\n");
exit(-1);
}
phead->data = -1;
phead->next = NULL;
return phead;
}
- Precautions:
- 1. After allocating the memory address space of the head node, be sure to check
内存分配是否成功
;
- 2. If the memory allocation of the head node fails, it needs to be used
shell命令exit(-1)退出
;
- 3. For the one-way linked list
每个结点都有数据域和指针域
, and 头结点的数据域可以不储存任何数据
for the head node 数据域
in this function, 被赋值 -1
;
- 4. For the head node
指针域被赋值 NULL
, it represents the one-way linked list at this time 只有一个头结点
;
- Method 2:
- The method used to
地址传参
create the head node of the one-way linked list, the code is as follows:
- Sample code:
int create_link_node_2(node_t **phead,int data){
if(NULL == phead){
printf("入参为NULL\n");
return -1;
}
*phead = (node_t *)malloc(sizeof(node_t));
if(NULL == *phead){
printf("内存分配失败\n");
return -1;
}
(*phead)->data = data;
(*phead)->next = NULL;
return 0;
}
- Precautions:
- 1. The parameter passed in must be
二级指针变量
, because 二级指针用来存储一级指针变量的地址
, namely 所申请的单向链表头结点在内存空间的地址
;
- 2. After the formal parameters are passed into the function function that creates the head node of the one-way linked list, it must be done
入参合理性检查
;
- 3. Same as method 1, after allocating the memory address space of the head node, be sure to check
内存分配是否成功
;
- 4. Head node
数据域被赋值 -1
;
- 5. Head node
指针域被赋值 NULL
;