我正在尝试删除双向链表中的节点,但问题是当我有列表时:7-6-5-4-3-2-1,并尝试删除3,我得到7-6-5-4-3,我无法弄清楚错误。请帮忙!
void RemoveItem(int itm)
{
if (Head->item == itm) {
Head = Head -> Next;
cout<<"\nItem is at 1st node & removed\n";flag=1;
}
else if (Head->Next == NULL) {
cout<<" \n This is 1-node list & item not in it\n";
}
else {
node *current, *del = Head;
while(del->Next != NULL && del->item != itm) {
del = del->Next;
}
current = del;
current->Next = del->Next;
del->Next->previous = current;
delete(del);
del->Next = NULL;
flag = 1;
}
}
答案 0 :(得分:0)
要删除您迭代的节点,直到到达删除del节点,然后设置: 伪代码:
del.prev.next = del.next
和
del.next.prev = del.prev
答案 1 :(得分:0)
这没有任何意义:
current = del;
current->Next = del->Next;
因为它与
相同del->Next = del->Next;
尝试这样的事情
// some global int flag = 0
// some global node* Head pointing to head of list
void RemoveItem(int itm) {
if (Head->item == itm) {
node* del = Head;
Head = Head -> Next;
delete(del);
cout<<"\nItem is at 1st node & removed\n";
flag=1;
return;
}
if (Head->Next == NULL) {
cout<<" \n This is 1-node list & item not in it\n";
return;
}
node* current = Head;
node* del = Head;
while(del->Next != NULL && del->item != itm) {
del = del->Next;
}
// reached with del->Next == NULL || del->item == itm
current = del->previous;
if (del->Next == NULL) {
// at end of list
if (del->item != item) {
// item not found
// todo: signal error
return;
}
current->Next = NULL;
} else {
del->Next->previous = current;
current->Next = del->Next;
}
delete(del);
flag = 1;
}
注意:我修复了很多错误并尝试将其保留在您的逻辑中。我会写不同的。