递归删除LinkedList C ++

时间:2015-10-08 00:08:27

标签: c++ recursion linked-list head

当我在C ++中删除节点对象时,有什么我忘记了吗? 我很困惑为什么我的删除方法适用于主要方法,但在测试时我的教授的主要方法不起作用。

这是我的一些删除方法的代码。

  1. 必须是递归的
  2. 必须取消分配内存,而不仅仅是移动指针。
  3. // this is his method header
    void remove (const E& x) {
       // passes in the head pointer, and the object to delete.
        _remove(head, x);
    }
    
    // Recursive remove function
    void _remove(Node* &curr, const E& val){
        // if the head is null do nothing.
        // base case
        if (curr == NULL){
            return;
        }
    
        //case where the node found is the head.
        if (curr->data == val && curr == head){
            head = head->next;
            delete curr;
            return;
        }
    
        // the node may be in the middle somewhere
        if (curr->next->data == val){
            Node* del = curr->next;
            curr->next = del->next;
            delete del;
            return;
        }
        // rinse and repeat.
        _remove(curr->next, val);
    }
    

0 个答案:

没有答案