Linked lists - single or double pointer to the head

前端 未结 3 1804
暖寄归人
暖寄归人 2021-01-16 09:57

We are given a task and a struct of linked list:

typedef struct dlistint_s
{
    int n;
    struct dlistint_s *prev;
    struct dlistint_s *next;
} dlistint_         


        
3条回答
  •  囚心锁ツ
    2021-01-16 10:34

    The reason to pass pointer to pointer to head is that any modification to the pointer head will be seen in the caller function and you do not have to return head from your function.

    For example, consider this simple node:

    struct Node{
        int data;
        struct Node *next;
    };
    

    A function to add a node to the list at front

    struct Node *add_node (struct Node *list, int n){
        struct Node *new_node = malloc(sizeof(struct Node));
        if(new_node == NULL){
            printf("Memory allocation failed\n");
            exit(EXIT_FAILURE);
        }
        new_node->data = n;
        new_node->next = list;
        return new_node;
    }
    

    If we need to assign the new_node to the list instead of returning it then we need to modify the above function and remove the return statement and put a statement

    list = new_node;
    

    But, that will not work!
    This is because in C, like all arguments, pointers are passed by value. That means the list contains the copy of the pointer value passed to add_node function and not the pointer passed to this function itself.
    That's where we need pointer to pointer.

    void add_node (struct Node **list, int n){
        struct Node *new_node = malloc(sizeof(struct Node));
        if(new_node == NULL){
            printf("Memory allocation failed\n");
            exit(EXIT_FAILURE);
        }
        new_node->data = n;
        new_node->next = *list;
        *list = new_node;
    } 
    

提交回复
热议问题