I'm having some trouble with my insertion method for a linked list in C. It seems to only add at the beginning of the list. Any other insertion I make fail. And this CodeBlocks debugger is so hard to understand I still don't get it. It never gives me value, just addresses in memory. Anyway this is my function. Do you see any reason why it's failing?
/* function to add a new node at the end of the list */
int addNodeBottom(int val, node *head){
//create new node
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}
newNode->value = val;
//check for first insertion
if(head->next == NULL){
head->next = newNode;
printf("added at beginning\n");
}
else
{
//else loop through the list and find the last
//node, insert next to it
node *current = head;
while(current->next != NULL)
{
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
}
current = current->next;
}
}
return 0;
}
Then in main, only 929 is added.
//testing addNodeBottom function
addNodeBottom(929, head);
addNodeBottom(98, head);
addNodeBottom(122, head);
addNodeBottom(11, head);
addNodeBottom(1034, head);
I would like to mention the key before writing the code for your consideration.
//Key
temp= address of new node allocated by malloc function (member od alloc.h library in C )
prev= address of last node of existing link list.
next = contains address of next node
This works fine:
Example usage:
The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till end and then change the next of last node to new node.
This code will work. The answer from samplebias is almost correct, but you need a third change:
Change 1:
newNode->next
must be set toNULL
so we don't insert invalid pointers at the end of the list.Change 2/3: The loop is changed to an endless loop that will be jumped out with
break;
when we found the last element. Note howwhile(current->next != NULL)
contradictedif(current->next == NULL)
before.EDIT: Regarding the while loop, this way it is much better:
After you
malloc
anode
make sure to setnode->next = NULL
.I should point out that with this version the
head
is still used as a dummy, not used for storing a value. This lets you represent an empty list by having just ahead
node.