我正在写一个简单的函数来插入C++链表的末尾,但最后它只显示第一个数据。我无法弄清楚什么是错的。这是函数:在链表的末尾插入
node* Insert(node* head, int data)
{
if (head == NULL) {
head = new node();
head->data = data;
head->link = NULL;
return head;
}
else {
node* temp = head;
while (temp != NULL) {
temp = temp->link;
}
node* temp2 = new node();
temp2->data = data;
temp2->link = NULL;
(temp->link) = temp2;
return head;
}
}
在'(temp-> link)= temp2;','temp'是一个空指针(如果它不是,你仍然在'while(temp!= NULL)'循环中旋转)。所以你解引用了一个空指针,它是UB。 – melpomene
非常感谢!:) – mistletoe