2013-12-19 75 views
0

我的函数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检查= 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

有趣的是(至少对我来说),当我最终没有释放温度时,它就起作用了!但是,我仍然在泄漏...... – Bourezg

+0

当你说Valgrind告诉你你正在泄漏,但你找不到它时,你使用什么参数以及Valgrind输出是什么? – kbshimmyo

+1

你不应该需要释放温度。 – Duck

回答

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。