2013-03-19 74 views
2

我的程序使用链表按顺序输入数字。删除整个链表C

My input: 2 4 23 34 534 543 

当我去删除列表中我得到这个:

137429056 137428992 137429040 137429024 137429008 0 

这是为什么?

void deleteList(node* head) 
{ 
    if(head == NULL) 
     printf("List is empty\n"); 

    else 
     deleteList(head->next); 

    free(head); 
} 

回答

6

你释放内存,但你没有设置任何的链接(或头本身)为空的,所以你引用未分配的内存。

另外:为什么使用递归时while循环会更简单?

+1

我认为递归更简单。虽然效率较低! – Claudiu 2013-03-19 02:41:11

+0

@Claudiu +1递归是否意味着简单是一个辩论问题,尽管我在这种情况下同意你的意见:) – 2013-03-19 02:43:26

+0

使用递归,因为这是分配。但非常感谢你的回答。 – juice 2013-03-19 02:43:51

1

这可能是一个非常古老的问题,但这个答案可以帮助某人。

deleteList(struct node* temp) 
{ 
    if(temp == NULL) 
      printf("List is empty\n"); 

    else { 
      head = temp; 
      temp->next = NULL; 
      free(temp); 
      deleteList(head->next); 
    } 
    head = NULL; 
}