Search code examples
cpointersqueuepass-by-referencesingly-linked-list

What is the role of the Node ** list double pointer in the enqueue function for queues using linked list?


I was asked to implement a queue using a linked list without a header node. My teacher gave us this snippet for referring to the enqueue function. I'm familiar with how to use queue operations. But I keep getting confused when double-pointers are used along with functions. I'm not sure which variable the double-pointer points to in most cases. I would like to know what Node ** list means.

Any help or explanation is appreciated

Here is the snippet that I referred

void insertNode(Node * prev,int x) {
    Node * new = (Node *) malloc(sizeof(Node));
    new->val = x;
    new->next = prev->next;
    prev->next = new;
}

void enqueue(Node ** list, int x) {
    Node * new = (Node *) malloc(sizeof(Node));
    if (isEmpty(*list)) {
        *list = new;
        (*list)->val = x;
        (*list)->next = NULL;
    }
    else {
        new = *list;
        while (new->next != NULL) 
            new = new->next;
        insertNode(new,x);
    }
}

Solution

  • Usually double pointers as parameters of functions is used to modify the pointer itself.

    Example:

    int a = 5;
    int b = 10;
    
    void foo(int *x)
    {
        x = &b;
    }
    
    void bar(int **x)
    {
        *x = &b;
    }
    
    
    int main(void)
    {
        int *ptr = &a;
    
        foo(ptr);
        printf("%d\n", *ptr);
    
        bar(&ptr);
        printf("%d\n", *ptr);
    }
    

    Output:

    5
    10
    

    Function bar modifies the pointer ptr. Function foo does not as x is a local variable having the function scope.