gpt4 book ai didi

c - 删除链表中的节点在c中不起作用

转载 作者:行者123 更新时间:2023-11-30 21:20:49 26 4
gpt4 key购买 nike

我想从链表中删除一个节点。但它不起作用。这是我的代码:

jL Delete(jL* node,int n)
{
jL first1, n_th, save;
int count = 0;
save = first1 = n_th = (*node);
while(first1->next)
{
first1 = first1->next;
count++;
if(count == (n-1))
break;
}


while ( first1->next != NULL )
{
first1 = first1->next;
save = n_th;
n_th = n_th->next;
}

save->next = n_th->next;
free(n_th);
return (&node);}

我的错误在哪里?你能帮我吗

最佳答案

您似乎想要以下内容。我认为列表中元素的索引从 0 开始。

jL Delete( jL* node, int n )
{
jL current = *node;
jL prev = NULL;

while ( current != NULL && n != 0 )
{
prev = current;
current = current->next;
--n;
}

if ( n == 0 && current != NULL )
{
if ( prev == NULL ) *node = current->next;
else prev->next = current->next;

free( current );
}

return *node;
}

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com