在此代码:为什么在复制链表时这个指针被赋值?
Node *CopyList(Node **head) {
Node *current = *head;
Node *NewNode = NULL;
Node *tail = NULL;
while (current != NULL) {
if (NewNode == NULL) {
NewNode = malloc(sizeof(Node));
NewNode->data = current->data;
NewNode->next = NULL; // routine
tail = NewNode;
} else {
tail->next = malloc(sizeof(Node)); // here
tail = tail->next;
tail->data = current->data;
tail->next = NULL;
}
current = current->next;
}
return(NewNode);
}
为什么我们分配tail->next
到malloc()
调用的结果?很显然,如果我们不这样做,会发生分段错误。
为什么我们不是只分配tail
而不是tail->next
?有什么情况下我应该这样分配?
这段代码看起来很合理。在第一次迭代中,它分配新列表的头部('NewNode'),并在每个后续迭代中扩展新列表的尾部。你认为这是什么错误?由于'tail',不应该有段错误,因为它在使用时不会为NULL。这里唯一错误的是'malloc'的返回值没有被检查为NULL。 – JS1
我没有想到这个错误,只是我没有得到它的方式。 –