Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C中链接列表中删除节点后释放节点_C_Free - Fatal编程技术网

如何在C中链接列表中删除节点后释放节点

如何在C中链接列表中删除节点后释放节点,c,free,C,Free,我有一个非常基本的疑问。我使用结构创建了一个链接列表,这是我的删除代码 void delete(int num) { struct node* temp=head; struct node* prev=head; if(temp == NULL) printf("List Empty\n"); else { while(temp != NULL) { if(temp->value == num) { prev=temp->next;

我有一个非常基本的疑问。我使用结构创建了一个链接列表,这是我的删除代码

void delete(int num)
{
struct node* temp=head;
struct node* prev=head;
if(temp == NULL)
printf("List Empty\n");
else
{
while(temp != NULL)
{
    if(temp->value == num)
    {
            prev=temp->next;
            free(temp);     
            break;
    }
    else
    {       
            prev=temp;
            temp=temp->next;        

    }
}
运行此代码后,不会删除节点。如果我在空闲(temp)后打印temp->value,则值为0。但事实并非如此。空闲节点应擦除该节点。所以我不明白0是从哪里出现的。你知道这个代码有什么问题吗

我的表演功能:

void show()
{
struct node *temp = head;
while(temp != NULL)
{
printf("----  %d  ---- ", temp->value);
temp=temp->next;
}
printf("\n\n");
}
我的结构:

struct node
{
int value;
int pos;
struct node* next;
};

谢谢。

当您在
删除中找到节点时:

if(temp->value == num)
{
        prev=temp->next;
        free(temp);     
        break;
}
实际上,您不会使上一个节点的下一个指针指向下一个链接的节点

相反,你应该这样做

prev->next = temp->next;

酷。这将处理除头部外的所有情况。如果删除第一个元素,我仍然得到0。所以,根据我的代码,如果我删除了temp,那么head也会被删除吗?我是否需要放置特殊条件来处理第一个节点的删除?如果(temp==head){head=temp->next;}此条件将处理该情况。谢谢