I am trying to create a link list. I wanted to know how these two codes are different? Code1: if (start == NULL) { start = newnode; } else { temp = start; while(temp != NULL) { temp = temp->next; }
temp = newnode;
}
Code2: if (start == NULL) { start = newnode; } else { temp = start; while(temp->next != NULL) { temp = temp->next; }
temp->next = newnode; }
}
Please fix this, i can't understand the code!!!
I don't think Code1 should work. You say
while(temp != NULL) temp = temp->next
. So when you come out of the loop temp is NULL. Now you try and assign newnode to temp which is pointless.Code2 on the other hand does what you want i.e. insertion. You say
while(temp->next != NULL) temp = temp->next
. So when you break out of the loop temp points to the last element in your list(since temp->next is NULL). Now you say temp->next = newnode which makes sense.