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

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,


1→ 2→ 3→ 4→ 5→ 6

Searching for ‘7’


Not Present

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


1→ 2→ 3→ 4→ 5

Searching for ‘2’



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.


 Live Demo

using namespace std;
using namespace std;
class node{
   int data;
   node(int 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){
      return false;
      return true;
      return searchRecursive(head->next, key);
void printNode(node*head){
int main(){
   node*head= NULL;
      cout<<"Not Present"<<endl;


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”.

Updated on: 05-Feb-2021


Kickstart Your Career

Get certified by completing the course

Get Started