我浏览了一些解释双链表中节点删除的文章,但我无法理解为什么以下代码无效 . 请提出一些解决方案 .
我有两个结构A和B.有一个结构链接列表A每个包含一个双向链表B.我试图从每个A中删除所有ID小于值的B结构 . 这是我试图这样做的方式 .
typedef struct __B {
int id;
struct __B *next;
struct __B *prev;
} B;
typedef struct __A {
B *bList;
struct __A *next;
} A;
void DeleteNodes(int value, A* AList) {
while(AList != NULL) {
B *BList = AList->bList;
while(BList != NULL) {
B *temp = BList;
BList = BList->next;
if(temp->id < value) {
if(temp->prev == NULL) // delete first node
BList->prev = NULL;
else {
temp->prev->next = BList;
temp->next->prev = temp->prev;
}
temp->next = NULL;
temp->prev = NULL;
free(temp);
temp = NULL;
}
}
AList = AList->next;
}
}
但是当我遍历AList和相应的BLists时,显然删除的节点仍然存在,导致应用程序崩溃 . 请分享一些建议 .
2 回答
您没有在while循环中更新
AList->bList
,这就是为什么它一直指向已删除的项目 . 更改代码以更新AList->blist
您忘记将AList-> bList设置为列表的新头部 .
当你释放()
temp
指向的内容时,你还需要确保指针AList-> bList指向列表中的下一个项目 . 由于您没有更新它,它会一直指向现在的free()d BList项并呈现未指定的结果 .在
AList = AList->next;
之前将AList->bList
设为BList