我写这个方法来删除链表的重复元素,但它显示了分段错误,为什么?

时间:2017-04-18 05:55:49

标签: c++ c data-structures linked-list

Node* RemoveDuplicates(Node *head)
{
    if (head == NULL || head->next == NULL)
    {
        return head;
    }
    else
    {
        Node *ptr = head;
        Node *tmp = head->next;
        int a = ptr->data;
        int b = tmp->data;
        while (ptr->next != NULL)
        {
            if (a == b)
            {
                while (a == b)
                {
                    ptr->next = tmp->next;
                    tmp = tmp->next;
                }
            }
            else
            {
                ptr = ptr->next;
                tmp = tmp->next;
            }

        }
        return head;
    }
}

GDB OUTPUT:

GDB trace:
Reading symbols from solution...done.
[New LWP 11656]
Core was generated by `solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  RemoveDuplicates (head=0x150fd00)
    at solution.cc:31
31            ptr->next=tmp->next;
#0  RemoveDuplicates (head=0x150fd00)
    at solution.cc:31
#1  main () at solution.cc:80

我在hackerrank上写了这段代码并显示了以下输出,真的无法理解为什么,请有人帮助我!

2 个答案:

答案 0 :(得分:1)

看看这段代码:

        if (a == b)
        {
            while (a == b)
            {
                ptr->next = tmp->next;
                tmp = tmp->next;
            }

a等于b时,您执行while (a == b)。由于您不会在a的正文中更改bwhile,因此您将拥有无限循环。

迟早tmpNULL,您的程序崩溃。

您可能希望在循环内更新ab。此外,您需要在执行NULL

之前检查ptr->next = tmp->next

答案 1 :(得分:0)

如果bifif (a == b) { while (a == b) { ptr->next = tmp->next; tmp = tmp->next; } 条件下相同,则tem = tmp-> next会出现分段错误。

a

如果belse不相同,那么tmp = tmp -> next条件else { ptr=ptr->next; tmp=tmp->next; } 会导致细分错误。

a

因为ba在整个循环中保持不变。此逻辑仅检查前两个节点的值。 确保在检查一个节点后,必须更改b</Project>值。