Search an element in the given singly Linked List using C++

C++Server Side ProgrammingProgramming

Given a singly linked list, the task is to search a particular element in the linked list. If the element is found, then print “present” otherwise “Not present”. For example,

Input-1

1→ 2→ 3→ 4→ 5→ 6

Searching for ‘7’

Output

Not Present

Explanation − In the given singly linked list the element ‘7’ is not present, hence we will return the output as “Not Present”.

Input-2

1→ 2→ 3→ 4→ 5

Searching for ‘2’

Output

Present

Explanation − Since in the given Singly linked list the element ‘2’ is present thus we will return the output as “Present”.

Approach to solve this problem

There are two approaches to search a particular element in the given singly linked list; we have to check recursively whether one element is present in the linked list or not.

If the linked list is empty, we will return false otherwise if the current node having the data value is equal to the input element then we will return true. In the other approach, we check the element iteratively if it equals the current head pointer or not and return true or false accordingly.

  • Take Input and Initialize a singly linked list by inserting nodes in it.

  • A Boolean recursive function searhRecursive(node*head, int element) takes the head pointer of the linked list and the key element as a parameter.

  • Initially if the head is NULL or if the linked list is empty then return false.

  • If the element to be searched is equal to the current head of the linked list then return true.

Example

 Live Demo

#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
class node{
public:
   int data;
   node*next;
   node(int d){
      data=d;
      node*next= NULL;
   }
};
void insertAt(node*&head, int data){
   node*n= new node(data);
   n->next= head;
   head= n;
}
bool searchRecursive(node*head,int key){
   if(head==NULL){
      return false;
   }
   if(head->data==key){
      return true;
   }
   else{
      return searchRecursive(head->next, key);
   }
}
void printNode(node*head){
   while(head!=NULL){
      cout<<head->data<<"->";
      head=head->next;
   }
   cout<<endl;
}
int main(){
   node*head= NULL;
   insertAt(head,5);
   insertAt(head,4);
   insertAt(head,3);
   insertAt(head,2);
   insertAt(head,1);
   printNode(head);
   if(searchRecursive(head,7)){
      cout<<"present"<<endl;
   }
   else{
      cout<<"Not Present"<<endl;
   }
}

Output

Running the above code will generate the output as,

Not Present

Since in the given linked list 1→2→3→4→5 the element ‘7’ is not present thus we return “Not Present”.

raja
Published on 05-Feb-2021 10:30:55
Advertisements