PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] 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

 July 05, 2022     c++, function-definition, linked-list, pass-by-reference, singly-linked-list     No comments   

Issue

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;
}


Answered By - Vlad from Moscow
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing