delete Duplicates单链表C.

时间:2013-11-13 19:16:10

标签: c singly-linked-list

我正在尝试使用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;

}

3 个答案:

答案 0 :(得分:1)

问题在于内循环条件和赋值

runner = runner->next;

由于您只有两个节点,并且删除了最后一个节点,因此上述分配会使runner等于NULL。然后在循环条件中检查runner->next

在调试器中很容易找到 very ,特别是如果你用它来逐行遍历代码来查看发生了什么。我建议你下次试试。

答案 1 :(得分:1)

它是segfaults的原因是:在内部while循环的第一次迭代结束时,runner的值为null,并且调用操作 - > next会导致segfault。

逐步阐述上述情况:

您有两个节点的链接列表。在下面的内部while循环开始时,

runner points to the first node,       
runner->next points to second node, and    
runner->next->next points to null

在第一次迭代结束时,只有一个节点,因此,runner-> next为null。 (在第一个评论if语句之后)为runner分配了runner-> next的值。所以runner的值现在为NULL。

在下一次迭代开始时,check runner-> next会导致segFault,因为runner是NULL。

- 另外,为了确保你的函数适用于空列表,你应该检查if(!head)而不是if(!* head)

答案 2 :(得分:0)

问题似乎在于对runner-> next的NULL检查。当您为列表中的最后一个节点执行这两行时,您的运行器将变为NULL。

runner->next = runner->next->next;< --- Runner的下一个是NULL。

.....

runner = runner->next;< - Runner现在为NULL。

在下一次迭代中,跑步者 - >接下来崩溃。 while循环条件应该是这样的: while(runner & runner->next)

-MS