gpt4 book ai didi

c - 如何删除一个节点

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:21:11 25 4
gpt4 key购买 nike

我正在尝试从列表中删除一个节点。我必须使用我用于从列表中删除第一个节点的函数,然后我必须添加其他节点(在我想删除的节点之前)。函数删除列表开头的节点并添加到列表的开头。

我试过这段代码:

List* Delete_theNode(int the_node){

List *temp;

if(head->next == NULL)
{
printf("empty list..");
}

else
{
for(temp = head; temp!= NULL; temp = temp-> next)
{
Delete_node();
}
if(temp->number == the_node)
{
Delete_Node();
}

else
{
printf("\n%d there is no such a node\n", the_node);
}

}
}

最佳答案

你的代码中有很多错误!

这个结构更像是一个链表而不是一个

您需要知道前一个节点才能删除该节点并将列表与下一个节点再次链接。

此外,您可能必须在删除节点之前释放已删除节点上的内存。

理想情况下:

Stack* Delete_theNode(int the_node) {
//check if it is on the head
if (the_node==head->number) {
Stack * temp = head;
head = head->next;
free(temp);
return;

}

Stack* cur = head->next;
Stack* prev = head;
//while cur is not NULL and prev is not NULL, this is also legit
while (!cur && !prev) {
if (the_node == cur->number) {
Stack *tmp = cur;//the deleted node
prev->next = cur->next;
free(tmp);
return;
}
prev = cur;
cur = cur->next;
}
}

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

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