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; }
Edit 1: newNode->next should be set to NULL , so we do not insert invalid pointers at the end of the list.
Edit 2/3: the loop changes to an infinite loop that will slip out with break; when we find the last item. Notice how while(current->next != NULL) used to be rejected if(current->next == NULL) .
EDIT. As for the while loop, this is much better:
node *current = head; while (current->next != NULL) { current = current->next; } current->next = newNode; printf("added later\n");
schnaader
source share