我试图从链表中删除重复项,所以如果列表以[1,1,2,3,4,4,5,5]开头,则附加列表为[1,2,3,4, 5].代码如下.
struct node_h
{
int data;
struct node_h* next;
} node;
void remove_h(node* head)
{
while (head != NULL)
{
if (head->data == head->next->data)
{
if (head->next->next == NULL)
{
head->next = NULL;
}
else
{
head->next = head->next->next;
}
}
head = head->next;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是它的分段错误.有时.
罪魁祸首是if (head->data == head->next->data)...如果head->next为null,这必须是段错误.
首先检查这个条件,如果是真的话,不能重复:只需if (head->next == NULL) break;在while中添加第一个语句或调整while条件.