2013-12-19 106 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。