如何在双向链表中实现擦除方法

时间:2014-01-31 23:57:55

标签: c++ erase doubly-linked-list

我必须编写一个双向链表,我正在尝试实现erase(Type obj)方法,该方法接受参数obj并遍历列表并删除具有元素obj的每个节点。

我面临的问题是,我正在从前面迭代链表,当我找到具有obj元素的节点时,我用obj元素更改节点前后节点的下一个/前一个指针。但是我不是用obj本身删除节点,据我所知c ++没有垃圾收集,所以有obj的节点仍然悬浮在空中。如何删除它?

我的擦除()

template <typename Type>
int Double_list<Type>::erase( Type const &obj ) {
if (empty()){
    return 0;
}
if (size() == 1 && head()->retrieve() == obj){
    list_head = nullptr;
    list_tail = nullptr;
    list_size--;
    return 1;
}

//Counter to hold the number of items deleted
int count = 0;
    //Iterating through the linked list
for (Double_node<Type> *ptr = head(); ptr != nullptr; ptr = ptr->next()){
    if (ptr->retrieve() == obj){
        ptr->previous_node->next_node = ptr->next();
        ptr->next()->previous_node = ptr->previous();
        count++;
        // delete ptr; // This stops me from iterating through the for loop
        list_size--;
    }
}
return count;
}

2 个答案:

答案 0 :(得分:1)

当您遍历列表时,您正在使用指向Double_node<Type> *类型的节点的指针,这意味着它已在某处分配,可以使用简单的delete ptr删除,但是因为您是使用它来获取列表中的下一个元素你必须要小心并过早地记住它,所以它应该是这样的:

Double_node<Type> *ptr_next = 0;
for (Double_node<Type> *ptr = head(); ptr != nullptr; ptr = ptr_next) {
     ptr_next = ptr->next ();
     if (ptr->retrieve() == obj){
     if (ptr->previous_node)
       ptr->previous_node->next_node = ptr->next();

     ptr->next()->previous_node = ptr->previous();
     count++;
     list_size--;
     delete ptr;
    }

我相信应该这样做。

答案 1 :(得分:0)

删除名为delete的指针和对象时有一种语法。 示例代码:

obj *temp = getCurrentNode();
//set pointers in nodes to the correct places
delete temp; //This releases all of the memory used in the object back to the OS
temp = NULL;//good practice to set this to null, since it points to non-allocated memory
//but exiting the function will make the pointer 'temp' useless, anyway.