C linked list inserting node at the end
After you malloc
a node
make sure to set node->next = NULL
.
int addNodeBottom(int val, node *head)
{
node *current = head;
node *newNode = (node *) malloc(sizeof(node));
if (newNode == NULL) {
printf("malloc failed\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL;
while (current->next) {
current = current->next;
}
current->next = newNode;
return 0;
}
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 a head
node.
This code will work. The answer from samplebias is almost correct, but you need a third change:
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;
newNode->next = NULL; // Change 1
//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 (true) { // Change 2
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
break; // Change 3
}
current = current->next;
};
}
return 0;
}
Change 1: newNode->next
must be set to NULL
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 how while(current->next != NULL)
contradicted if(current->next == NULL)
before.
EDIT: Regarding the while loop, this way it is much better:
node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
I know this is an old post but just for reference. Here is how to append without the special case check for an empty list, although at the expense of more complex looking code.
void Append(List * l, Node * n)
{
Node ** next = &list->Head;
while (*next != NULL) next = &(*next)->Next;
*next = n;
n->Next = NULL;
}