删除LinkedList中的front元素会产生垃圾



这是代码:

void deleteNodebyValue(struct Node *head, int data){
    Node *cur = head;
    Node *prevNode = head;
    while(cur){
        if(cur->data == data){
            //cout << "if(cur->data == data)" << endl;
            if(cur == head){
                cout <<"if(cur == head)" << endl;
                //head = cur->next;
                return;
            } else{
                prevNode->next = cur->next;
            }
            delete cur;
            return;
        }
        prevNode = cur;
        cur = cur->next;
    }
}

它适用于除前(第一个/头)节点之外的任何节点。如果我试图删除第一个节点,它会产生垃圾:(.

如果您试图修改head在函数中指向的位置,问题是您通过值传递head,这意味着指针被复制,而在函数中您只在本地修改副本。您需要通过引用传递head指针:

void deleteNodebyValue(struct Node *&head, int data){...}

当然,在这种情况下,您不能直接返回,您仍然需要实际删除节点。

最新更新