+92 332 4229 857 99ProjectIdeas@Gmail.com

How to find the index of the desired element in a singly linked list (C++)


Finding data in the linked list
Find() takes the data to be searched as its input parameter and returns the index of the node at which the data is found. It returns -1 if the data is not found.
Index corresponds to the node number.
Summary of Find()
The logic is similar as used before in searching. The only difference is that a new variable index is introduced-which keeps record of the node number at which the data is found.
Node*tptr=head;
       int index=1;

              while(tptr!=NULL)
              {
                     if(tptr->data==valToFind)
                           return index;
                     tptr=tptr->link;
                     index=index+1;
              }
return -1;

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

struct Node
{
public:
       int data;
       Node*link;
      
       Node();
};

Node::Node()
{
       data=0;
       link=NULL;
}

class LinkList
{
public:
       Node*head;
       LinkList();
       void AddNodeAtEnd(int);
       int  Find(int);
};

LinkList::LinkList()
{
       head=NULL;
}

void LinkList::AddNodeAtEnd(int _data)
{
       Node*node=new Node();
       node->data=_data;
       node->link=NULL;
      
       if(head==NULL)
              head=node;
       else
       {
              Node*tptr=head;
              while(tptr->link!=NULL)
                     tptr=tptr->link;
              tptr->link=node;
       }
}

int LinkList::Find(int valToFind)
{
       Node*tptr=head;
       int index=1;

              while(tptr!=NULL)
              {
                     if(tptr->data==valToFind)
                           return index;
                     tptr=tptr->link;
                     index=index+1;
              }
return -1;
}

int main()
{
       LinkList l;

       // Adding first  element to the linked list
       l.AddNodeAtEnd(20);
       // Adding second element to the linked list
       l.AddNodeAtEnd(30);
       // Adding third  element to the linked list
       l.AddNodeAtEnd(40);

       cout << "20 found at index number : " << l.Find( 20 ) << endl;
       cout << "30 found at index number : " << l.Find( 30 ) << endl;
       cout << "40 found at index number : " << l.Find( 40 ) << endl;
      
       _getche();
       return 0;
}

Output
20 found at index number : 1
30 found at index number : 2
40 found at index number : 3

0 comments: