How do I delete a specific number from doubly linked list in c++?

Viewed 45

I was assigned to delete a number entered by user from a doubly linked list. So my code is successfully finding the number in the linked list and checking whether the linked list is empty or not but it is not able to delete it. It deletes the whole linked list instead of the number itself. I am unable to find the mistake. So kindly help me as I am literally stuck here. Here is my code:

void deleteSpcificValue(int val)
{
    int result = 0;
    Node *curr = head;
    if(head == nullptr)
    {
        curr = head;
        cout << "List Is Empty"<<endl;
    }
    else
    {
        while(curr != nullptr)
        {
            if(curr -> data == val)
            {
               cout << "Value Deleted" << endl;
                result = 1;
                curr = nullptr;
                delete curr;
            }
            curr = curr -> next;
        }
    }
   if(result != 1)
    {
        cout << "The Value To Be Deleted Is Not Found" <<endl;
    }

}
1 Answers

The function does not make sense because it does not update data members next and prev (I assume that you have the name prev or something similar for the pointer that points to the previous node)

Also it does not delete the found node because you set it to nullptr

curr = nullptr;
delete curr;

Also as after this code snippet the pointer curr is equal to nullptr then the following statement

curr = curr -> next;

invokes undefined behavior.

And if the deleted node is the head node then your function does not update the pointer to the head node.

Pay attention to that the function should not issue any message. It is the caller of the function that will decide whether to issue a message.

The function can be defined the following way

bool deleteSpcificValue( int val )
{
    Node *current = head;

    while ( current != nullptr && current->data != val )
    {
        current = current->next;
    }

    bool success = current != nullptr;

    if ( success )
    {
        if ( current->next != nullptr )
        {
            current->next->prev = current->prev;
        }
        // If the class has a pointer to the tail node
        //   then uncomment the else part  
        /*
        else
        {
            tail = current->prev;
        }
        */

        if ( current->prev != nullptr )
        {
            current->prev->next = current->next;
        }
        else
        {
            head = current->next;
        }

        delete current;
    }

    return success;
}
Related