我正在尝试在 C 中实现给定链表的 deleteDuplicates。我遇到了 segFault 的问题,我不知道为什么。我的测试用例给它一个带有两个节点的链表,每个节点都有数据 3 如下。在我的 deleteDups 中,您会看到两个被注释掉的 if 块。如果我取消注释,我不会有 segFault 并且代码似乎可以正常工作。
为什么会这样?在我看来,if 语句正是 while 循环检查的内容......
提前致谢!
我的节点结构和代码
typedef struct node{
int data;
struct node *next;
} *node;
void deleteDups(node *head)
{
if (!*head)
return;
node current = *head;
node runner;
while (current)
{
runner = current;
while (runner->next)
{
if (runner->next->data == current->data)
{
node tmp = runner->next;
runner->next = runner->next->next;
free(tmp);
}
/*if(runner->next == NULL)
{
break;
}*/
runner = runner->next;
}
/*if (current->next == NULL)
{
break;
}*/
current = current->next;
}
}
int main(int argc, char*argv[])
{
node one = (node) malloc (sizeof (struct node));
one->data = 3;
one->next = NULL;
node head = (node) malloc (sizeof (struct node));
head->data = 3;
head->next = one;
printList(head);
deleteDups(&head);
printList(head);
return 0;
}