Search code examples
c++linked-listpass-by-referencesingly-linked-listfunction-definition

How to make a function in C++ to delete a node from the linked list (node can be any except the first node) which matches the searched key


I have this function named DeleteData which I use to delete any node from my linked list.

void DeleteData(Node *node, int key)
{
   Node temp;
   //If key is in the first node itself
   if (node != NULL && node->read_data() == key)
   {
      temp = *node->next;
      node->next = NULL;
      delete node;
      cout << "New List";
      // It's just a function that reads all data from the linked list given the head reference.
      ListTraverse(&temp);
      return;
   }
   //If key is not in first node
else if (node->read_data() != key)
{
    while (node != NULL && node->read_data() != key)
    {
        // Function to loop thorugh all the nodes
    }
    if (node->read_data() == key)
    {
        //Steps to do, If node is found
    }
}
else
{
    cout<<"Invalid Search key";
}

}

This DeleteData is designed to take two arguments, 1. the reference of 1st node, 2. A key. I need to delete the node which has the matching key as its value. I have successfully made the 1st part i.e., when the key is in the 1st node only, but I am unable to design it so that if the key is not found in the 1st node it should on to search the remaining nodes.

Node is a C++ class having this definition

class Node
{
private:
  int data;

public:
  Node *next;
  void push_data(int x)
  {
      data = x;
  }
  int read_data()
  {
     return data;
  }
};

Solution

  • For starters the parameter that specifies the head node shall have a referenced type.

    The function can be declared and defined the following way

    bool DeleteData( Node * &head, int key )
    {
        Node **current = &head;
    
        while ( *current && ( *current )->read_data() != key )
        {
            current = &( *current )->next; 
        }
    
        bool success = *current != nullptr;
    
        if ( success )
        {
            Node *tmp = *current;
            *current = ( *current )->next;
            delete tmp;
        }
    
        return success;
    }