+92 332 4229 857 99ProjectIdeas@Gmail.com

How to search an element in a singly linked list (C++)


Searching data in the linked list
Search() takes the data to be searched as its input parameter and returns 1 if the data is found and returns 0 in case if the data is not found in the linked list.
Summary of Search()
The logic behind searching is very simple. There is a loop which iterates from the start of the linked list and searches till end. If the data is found then 1 is returned from the function and the loop terminates. If the data is not found then the last statement of this function will execute and returns 0.
Node*tptr=head;
              while(tptr!=NULL)
              {
                     if(tptr->data==valToSearch)
                           return true;
                     tptr=tptr->link;
              }
return false;

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);
       bool Search(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;
       }
}

bool LinkList::Search(int valToSearch)
{
       Node*tptr=head;

              while(tptr!=NULL)
              {
                     if(tptr->data==valToSearch)
                           return true;
                     tptr=tptr->link;
              }
return false;
}

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 << l.Search( 10 ) << endl;
       cout << l.Search( 20 ) << endl;
       cout << l.Search( 30 ) << endl;
       cout << l.Search( 40 ) << endl;
       cout << l.Search( 50 ) << endl;

       _getche();
       return 0;
}

Output
0
1
1
1
0

0 comments: