codolove's blog

By codolove, 9 years ago, In English

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;
    }

}

  • Vote: I like it
  • +6
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
  Vote: I like it -11 Vote: I do not like it

Please fix this, i can't understand the code!!!

»
9 years ago, # |
  Vote: I like it +8 Vote: I do not like it

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.