我的函数remove_duplicates应该删除链表中的重复数据值。但是,当它到达链接列表中的某个点时,例如,如果链接列表为L = {10,10,20,30,30,30,40,50}
,则输出为L = {10,20,30,(some random int value like 23687328),50}
时应为L = {10,20,30,40,50}
。另外,我正在检查泄漏,Valgrind告诉我,我正在某处泄漏,但我找不到它。
typedef struct node_t
{
int data;
struct node_t *next;
} node;
void remove_duplicates(node * head)
{
node* temp;
while (head != NULL && head->next != NULL)
{
while (head->data == head->next->data)
{
temp = head->next->next;
free(head->next);
head->next = temp;
}
head = head->next;
}
free(temp);
}
我正在使用valgrind --leak-check = yes ./llistprac,输出是
==24802== 80 (16 direct, 64 indirect) bytes in 1 blocks are definitely lost in loss record 5 of 5
==24802== at 0x4A069EE: malloc (vg_replace_malloc.c:270)
==24802== by 0x400575: append (in /home/llistprac)
==24802== by 0x4006D9: main (in /home/llistprac)
==24802==
==24802== LEAK SUMMARY:
==24802== definitely lost: 16 bytes in 1 blocks
==24802== indirectly lost: 64 bytes in 4 blocks
==24802== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)
答案 0 :(得分:0)
void remove_duplicates(node * head)
{
node* temp;
while (head != NULL && head->next != NULL)
{
if (head->data == head->next->data)
{
temp = head->next;
head->next = head->next->next;
free(temp);
}
else
head = head->next;
}
}
每次删除节点或移动到下一个节点时,都应该检查head-next是否为NULL。