Search code examples
c++ooplinked-listsingly-linked-listfunction-definition

I have created function to modify a node in Linkedlist in C++ but its not working:


This Function is Created in LinkedList to modify a node at a given position. But, this function is not working properly and it is giving some random values.

  void update_data(int old, int new_data) {//Function toupdate node
                Node *curr=header;//Data members
               int pos = 0;
               while(curr->next!=NULL) {
                  if(curr->isbn == old)
                  {
                     curr->isbn = new_data;
                     cout<<old<<" Found at position "<<pos<<" Replaced with "<<new_data<<endl;;
                  }
                  curr = curr->next;
                  pos++;
               }
               }

Solution

  • For starters the variable pos is not used within the function.

    Secondly the condition of the while loop

    while(curr->next!=NULL) {
    

    is incorrect and in general can invoke undefined behavior because the pointer header can be equal to nullptr. And moreover if the list contains only one node pointed to by the pointer header and its data member isbn is equal to the value of the variable old it will not be changed.

    The function should not output any message.

    The function can look the following way

    void update_data( int old, int new_data ) 
    {//Function toupdate node
        for ( Node *curr = header; curr != nullptr; curr = curr->next ) 
        {
            if ( curr->isbn == old )
            {
                curr->isbn = new_data;
            }
        }
    }