2013-03-19 31 views
1
[email protected]:~/C$ ./ccarri7lab9 
q: quit the program 
i: inserts an integer value 
d: deletes an integer value 
c: checks if an integer value is in the list 
e: deletes all integers from the list 
l: lists the items in the list (small to big) 
r: lists the items in reverse order (big to small) 

Please make a choice: i 
Enter the value you want to insert: 3 
Please make another choice: i 
Enter the value you want to insert: 4 
Please make another choice: i 
Enter the value you want to insert: 5 
Please make another choice: l //lists integers 
3 4 5 
Please make another choice: e //deletes list 
Please make another choice: l //lists integers 
137904144 137904160 0  // output 
Please make another choice: q 

除了我的刪除列表功能,一切正常。出於某種原因,它應該釋放每個節點時輸出垃圾(從而釋放整個鏈表)。每個函數都必須遞歸地完成(這是一個賦值)。當我刪除一個鏈表時,得到一個錯誤的輸出

void deleteList(node* head) 
{ 
    if(head) 
    { 
     deleteList(head->next); 
     free(head); 
    } 
} 
+0

在'free'ing之前,設置'head-> next'。 free 'ing後,將'head'設置爲NULL。 – 2013-03-19 07:14:16

回答

2

你刪除整個列表後,您需要將head指針設置爲NULL。否則,它會懸空,導致undefined behaviour當您嘗試打印列表。

爲了能夠在deleteList()中做到這一點,您需要更改函數head作爲雙指針(node**)。

+0

我也試過,它仍然輸出垃圾。我會再試一次。感謝您的快速回復 – juice 2013-03-19 07:12:49

+0

沒關係..我是個白癡。我有head == NULL而不是head = NULL:\謝謝。 – juice 2013-03-19 07:13:56

相關問題