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上写了这段代码并显示了以下输出,真的无法理解为什么,请有人帮助我!
答案 0 :(得分:1)
看看这段代码:
if (a == b)
{
while (a == b)
{
ptr->next = tmp->next;
tmp = tmp->next;
}
当a
等于b
时,您执行while (a == b)
。由于您不会在a
的正文中更改b
或while
,因此您将拥有无限循环。
迟早tmp
将NULL
,您的程序崩溃。
您可能希望在循环内更新a
或b
。此外,您需要在执行NULL
ptr->next = tmp->next
答案 1 :(得分:0)
如果b
和if
在if (a == b)
{
while (a == b)
{
ptr->next = tmp->next;
tmp = tmp->next;
}
条件下相同,则tem = tmp-> next会出现分段错误。
a
如果b
和else
不相同,那么tmp = tmp -> next
条件else
{
ptr=ptr->next;
tmp=tmp->next;
}
会导致细分错误。
a
因为b
和a
在整个循环中保持不变。此逻辑仅检查前两个节点的值。
确保在检查一个节点后,必须更改b
和</Project>
值。