c - 删除链表中的节点

标签 c linked-list

大多数代码都有效,但是当我尝试删除列表的最后一个元素并打印它时,我在它的位置看到了一些垃圾数据,我在这里做错了什么?有人可以指出我的错误吗?

void DeleteClient2(struct client *temp,struct client **head)
{   struct client *prev=*head;
    struct client *current = *head;
    struct item *currentitem = (*head)->item_data,*save;
    if(temp== *head)
    {
        while(currentitem != NULL)
        {
            save = currentitem;
            currentitem = currentitem ->next;
            free(save);
        }
        free(temp);
        temp->item_data = NULL;
        (*head) = (*head)->next;
    }
    else
    if(temp->next == NULL)
    {
        while(currentitem != NULL)
        {
            save = currentitem;
            currentitem = currentitem ->next;
            free(save);
        }
        temp->item_data = NULL;
        free(temp);
    }
    else
    if(temp != *head && temp->next != NULL)
    {
        while(prev->next != temp)
        {
            prev=prev->next;
        }
        prev->next = temp->next;
        while(currentitem != NULL)
        {
            save = currentitem;
            currentitem = currentitem ->next;
            free(save);
        }
        temp->item_data = NULL;
        free(temp);
        temp=temp->next;
    }
}

最佳答案

代码:

    free(temp);
    temp=temp->next;  // temp->next is invalid

是未定义的行为,一旦你释放了一个节点你就不能访问它,这样做是非法的。

关于c - 删除链表中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21300630/

相关文章:

c - 函数返回链表 - C

C 通过 char* 正确处理空终止符

将数字转换为字节数组

c - 检测宏是否无效

swift - 从反向链表中提取值

c++ - 删除链表中的节点后释放分配的空间

java - LinkedList 和 TreeMap : compareTo or equals?

c - 将 printf 语句分配给 int 变量

c - C上的系统编程

c++ - 链表在开头打印 0 值 c++