Linked lists - single or double pointer to the head

前端 未结 3 1809
暖寄归人
暖寄归人 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:27

    Because if you are using dlistint_t *head variable instead of using dlistint_t **head variable in function parameter then, changes made in variable head in function dlistint_t *add_dnodeint(dlistint_t **head, const int n); will be local to this method. Since you are using Node* so changes done in variable head is local to that function. If you want to reflect these changes even after function call(which you obviously wants to) then use dlistint_t **head.

    0 讨论(0)
  • 2021-01-16 10:33

    If you use a double pointer, you can pass in the address of the head so your functions can modify the actual pointer. This way you don't need to return the new head.

    0 讨论(0)
  • 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;
    } 
    
    0 讨论(0)
提交回复
热议问题