删除整个链表C.

时间:2013-03-19 02:36:58

标签: c recursion linked-list

我的程序使用链接列表按顺序输入数字。

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);
}

2 个答案:

答案 0 :(得分:6)

释放内存,但不要将任何链接(或头部本身)设置为null,因此您将引用未分配的内存。

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

答案 1 :(得分:2)

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

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;
 }