Linked list insertion not working for 0th index

69 Views Asked by At

I have wrote a c program for linked list, and a function to insert a node at an index. When calling the function for index 0, The head pointer doesn't seem to be updating in the main function even though i have updated it in the insertion function. The traverse function doesn't seem to be printing the newly added element. Please help.

Code:

Node struct Main function Function for traversing and printing the list Insertion function

Output:

After insertion output is still the same

1

There are 1 best solutions below

1
pts On

This is because when you insert at the beginning, you have to change the head pointer to point to the newly inserted element. For that to work, the insert_to_index function has to tell its caller (main function) what the new head is. Changing ythe value of the function parameter head inside insert_to_index is not enough, because that doesn't change the head in main.

One way to fix it is returning the new head value. To do that, change return; to return head; in insert_at_index (and change its return type from void to struct node*, and also add return head; to the end), and also change its call to head = insert_at_index(head, 0, 0); in main.

Another, alternative way to fix it is changing the parameter to struct node **head (two stars), changing head to *head within insert_at_index, and changing head to &head when insert_to_index is called from main.