gpt4 book ai didi

c - C中的双向链表,按值插入

转载 作者:太空宇宙 更新时间:2023-11-04 08:31:15 26 4
gpt4 key购买 nike

我决定在双向链表上做一个项目,以便更好地理解它。我已经制作了在头部和尾部插入节点的函数,但现在我无法按值插入节点。这是函数:

void f_insert_by_value(the_individual **head, char *str, int a) {
the_individual *current = *head, *temp = f_create(str, a);

if (*head == NULL) *head = temp;
else {
if (temp->age < (*head)->age) {
temp->next = (*head);
(*head)->prev = temp;
(*head) = (*head)->prev;
}
else {
while (temp->age > current->age && current->next != NULL) current = current->next;
if (current->next = NULL) {
temp->prev = current;
current->next = temp;
current = current->next;
}
else {
temp->prev = current->prev;
temp->next = current;
current->prev->next = temp;
current->prev = temp;
}
}
}
return;
}

段错误发生在行“current->prev->next = temp”。我尝试打印地址以查看为什么会发生这种情况,并发现输入中第一个节点总是以其前一个元素指向 NULL 告终。有人可以解释为什么会发生这种情况以及如何解决吗?谢谢。

最佳答案

在第一个节点上,current->prev 为空,因为 current 是第一个,你没看错。

temp->prev = current->prev;
temp->next = current;

这件事是对的,你在正确的地方设置了新的节点,但是现在 current 并没有导致正确的事情。此时你的架构是这个:

NULL <= temp => current
NULL <= current <=> ...

你想要

NULL <= temp <=> current <=> ...

所以唯一缺少的是 current 的前一个元素是 temp。所以我想只是删除行

current->prev->next = temp

应该为第一个元素插入做这个技巧,因为你在之后设置了 current->prev

所以我猜你的条件 block 应该是这样的:

temp->prev = current->prev;
temp->next = current;
if (current->prev != NULL) {
current->prev->next = temp;
}
current->prev = temp;

正如评论中所说,如果你想避免链表的空指针问题,你可以在列表的开头和结尾添加一个虚拟对象,它们是 Controller ,告诉你达到了限制。您可以找到有关这些类型的链表(带有 Sentinel 节点)的更多信息 here

关于c - C中的双向链表,按值插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28240307/

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