'why the head at main doest get the node?

im trying to insert node to the begging of link list but the value from poiter to poiter isnt passing i wrote a note ***** where the problem accure

void insertTolist(list* head, list* node)
{
    list* current = head;
    list* currentPlusOne = head->next;
    while (current->next != NULL)
    {
        if (current->data<node->data && currentPlusOne->data>node->data)
        {
            current->next = node;
            node->next = currentPlusOne;
            break;
        }
        if (current->data<node->data && currentPlusOne->next == NULL)
        {
            current->next = node;
            node->next = (list*)calloc(1, sizeof(list));
            break;
        }
        if (current->data > node->data && currentPlusOne->data >node->data)// b c 
        {
            node->next =current;
            head = node;// ***the head doesnt chanching at the main***
            break;
        }
        current = current->next;
        currentPlusOne = currentPlusOne->next;
    }
    //printlist(head);
}


Solution 1:[1]

The function declared like

void insertTolist(list* head, list* node)

deals with a copy of the value of the pointer to the head node used as an argument. Changing the copy in this statement

head = node;

is not reflected on the value of the original pointer.

Moreover the function can invoke undefined behavior if the passed pointer is a null pointer at least due to this declaration

list* currentPlusOne = head->next;

Also this statement

node->next = (list*)calloc(1, sizeof(list));

does not make a sense.

You need either to pass the pointer to the head node to the function by reference through a pointer to it or to return from the function the pointer (possibly modified) to the head node and to assign its value to the original pointer.

If to use the first approach then the function will look enough simple.

void insertTolist( list **head, list *node )
{
    while ( *head != NULL && !( node->data < ( *head )->data ) )
    {
        head = &( *head )->next;
    }

    node->next = *head;
    *head = node;
}

and if in the caller the pointer head is declared like

list *head = NULL;

then the function is called like

insertTolist( &head, node );

where node is a pointer to the inserted node in the list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1