Блог пользователя codolove

Автор codolove, 9 лет назад, По-английски

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

}

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
9 лет назад, # |
  Проголосовать: нравится -11 Проголосовать: не нравится

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

»
9 лет назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

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.