如何在双向链表指定索引处添加新节点及代码无限循环排查
双向链表插入节点导致无限循环的问题修复
问题根源分析
- 循环引用引发无限循环:你代码里的
new_node->next = temp;是核心错误。这会让新节点的next指向当前的temp节点,而temp->next又被设置为新节点,两者互相指向形成闭环,后续遍历链表时必然陷入无限循环。 - 双向链表结构不完整:插入节点时未处理原后继节点的
prev指针,若temp不是尾节点,原后继节点的prev没有指向新节点,破坏了双向链表的双向关联。 - 头部插入逻辑遗漏:当
idx=0时,若原链表不为空,没有将原头节点的prev指向新节点,也未让新节点的next指向原头节点,会丢失原链表且结构断裂。
修正后的代码
dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n) { dlistint_t *temp; dlistint_t *new_node; unsigned int count; temp = *h; new_node = malloc(sizeof(dlistint_t)); if (new_node == NULL) return (NULL); new_node->n = n; if (idx == 0) { new_node->next = *h; new_node->prev = NULL; if (*h != NULL) (*h)->prev = new_node; *h = new_node; return (new_node); } else { count = 0; while (temp != NULL && count != idx - 1) { temp = temp->next; count++; } if (temp == NULL) // 等价于count != idx-1,表述更直观 { free(new_node); // 释放已分配内存,避免泄漏 return (NULL); } new_node->next = temp->next; new_node->prev = temp; if (temp->next != NULL) temp->next->prev = new_node; temp->next = new_node; return (new_node); } }
额外说明
- 完善头部插入逻辑,处理原链表不为空的情况,保证双向关联正确。
- 插入中间节点时,正确设置新节点的
next为temp的原后继,并更新原后继的prev指针。 - 当索引超出链表长度时,释放已分配的新节点内存,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Stanley
相关产品推荐
相关产品推荐

