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
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
headinside insert_to_index is not enough, because that doesn't change theheadin main.One way to fix it is returning the new
headvalue. To do that, changereturn;toreturn head;in insert_at_index (and change its return type fromvoidtostruct node*, and also addreturn head;to the end), and also change its call tohead = insert_at_index(head, 0, 0);in main.Another, alternative way to fix it is changing the parameter to
struct node **head(two stars), changingheadto*headwithin insert_at_index, and changingheadto&headwhen insert_to_index is called from main.