Search code examples
c++linked-listnodes

linked list - searching node by value


its a self sorted node when i search the node by search(int x) function the program stops if the x > then the greatest node value ie last node value following is the program

   void search(int value)
      {
    if(!isEmpty())
    {

        loc = start;
        pedloc = NULL;
        int n=1;
        while(loc != NULL && loc->data < value)
        {
             pedloc= loc;
            loc = loc->next;
        n++;
        }

        if(loc != NULL && loc->data != value)
        {
            loc = NULL;
            cout<<"value not exist"<<endl;
            return;
        }

        cout<<"value "<<loc->data<<" is present at #" 
      <<n<<" node"<<endl;
    }

  }

Solution

  • Here is one of the ways you can identify the node by the value.

    void search(int value)
        {
            node *temp=new node;
            temp=head;
            int pos = 1;
            while(temp!=NULL)
            {
                if(temp->data == value)
                {
                    cout << "" << value << " is at position: " << pos << endl;
                    break;
                }
                else if (temp->next == NULL && temp->data != value)
                {
                    cout << "" << value << " is not part of the linked list" << endl;
                    break;
                }
                temp=temp->next;
                pos++;
            }
        }
    

    This sample code kind of matches with what you want to achieve. It is easier to find the node by the value while inside the loop. When the node is found, just break the loop. If we are at the last node and the value does not exist that means the value and subsequently the node is not part of the linked list which is what the "else if" condition is checking.