如何在不破坏列表的情况下删除链表中的节点?

时间:2012-03-05 23:37:04

标签: c++ memory-management linked-list

template <class T>
bool LinkedList<T>::remove(const T object){
  Node<T> *cur = head;
  while(cur->next != NULL){
    if(cur->next->value == object){
      Node<T>* temp = cur->next->next;
      delete cur->next;
      cur->next = temp;
      s--;
      return true;
    }
    cur = cur->next;
  }
  return false;
}

我在分配后删除了该对象。当我打印出值时,节点似乎被破坏了。这是从链表中删除项目的最佳方法吗?

2 个答案:

答案 0 :(得分:2)

  

节点析构函数只是“删除下一步”。

Oooops。如果每个节点在其析构函数中删除下一个节点,则会导致该点的整个列表被删除!

  Node<T>* temp = cur->next->next; // the node temp points to is clearly after cur
  delete cur->next; // deletes everything after cur
  cur->next = temp; // temp no longer points to a valid node

答案 1 :(得分:0)

工作版本看起来更像是这样:

template <class T>
bool LinkedList<T>::remove(const T object) {

    // Iterate through the list.
    for(Node<T> **cur = &head;; cur = &((*cur)->next)) {
        // Check for list end.
        if(!*cur)
            return false;
        // Check for match.
        if((*cur)->value == object)
            break;
    }

    // Knock out the node.
    Node<T> *temp = (*cur)->next;
    delete *cur;
    *cur = temp;

    // No idea what s does.
    --s;

    return true;
}