Ad

Inserting A New Node To A Singly Linked List Doesnt Work When I Call The Function In A Loop

I am trying to append a node to the end of a list, so I wrote a simple append_node function. This function works fine normally but when I use a for loop , a extra node with a undefined value gets stored into the head node.

Here is the code:

int main() {
    linked_list *list;

    append_node(&list, 4);
    append_node(&list, 20);
    append_node(&list, 200);

    print_linked_list(list);    // 4 20 200
                                //prints just fine
}

the code above works fine but when I do this below:

int main() {
    linked_list *list;

    for (int i = 0; i < 5; i++)
        append_node(&list, i);

    print_linked_list(list);   // 11342689 0 1 2 3 4
                               // prints a extra undefined node here at the head 
}

expected result: 0 1 2 3 4 actual result : 11342689 0 1 2 3 4

here is the append_node function:

void append_node(linked_list **head_ref, int value) {
    linked_list *current = *head_ref;

    linked_list *new_node = (linked_list *)malloc(sizeof(linked_list));
    new_node->node_value = value;
    new_node->next_node = NULL;

    if (*head_ref == NULL) {
        *head_ref = new_node;
        return;
    }

    while (current->next_node)
        current = current->next_node;

    current->next_node = new_node;
    return;
}

whenever I use a loop the list gets a new head with a undefined value.The rest of the list seems correct. I don't know why this happens. Can anyone please tell me? Thanks in advance :)

Ad

Answer

You should initialize the linked_list *list to NULL, and it should work just fine.

Ad
source: stackoverflow.com
Ad