Two ways to create one-way linked lists in the data structure learning series

  • 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);

    }
    //或者memset(phead, 0, sizeof(node_t));
    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;

    }
     //或者memset(*phead, 0, sizeof(node_t));
    (*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;

Guess you like

Origin blog.csdn.net/qq_41878292/article/details/132650574