双链表:删除Node C ++

时间:2012-12-23 19:02:17

标签: c++ linked-list

void DLinkedList::removeName(const Elem& name) {

 DNode * node = header;

 if (node != NULL) {
     do {
         if(node->elem == name){
             node->prev->next = node->next;  
             node->next->prev = node->prev;
             delete node;
         }
         node = node->next;
     } while (node != header); // Stop when we reach the head again.
 }

}

我把它扔进了调试器,在我第三次通过if(node-> elem == name)之后,它崩溃的原因我不太确定。

1 个答案:

答案 0 :(得分:0)

请注意如果条件为真,那么您delete node以及稍后在node->next取消引用它,导致未定义的行为,这是导致您崩溃的原因

     if(node->elem == name){
         node->prev->next = node->next;  
         node->next->prev = node->prev;
         delete node; // delete here
     }
     node = node->next; // dereference invalid pointer