Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

# Search an element in a Linked List (Iterative and Recursive)

Last Updated on March 9, 2022 by Ria Pathak

### Introduction

The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.

### Problem Statement

In this question, we are given a singly linked list and a value X. We have to check whether the given number X is present in the list or not.

### Problem Statement Understanding

Let’s try to understand the problem statement with the help of some examples by referring the best online c programming course.

and the value to be searched X=13.

• According to the problem statement, we have to check if the value X is present in the linked list or not. If it is present, we have to return true/Yes; otherwise, we must return false/No.
• As we can see, 13 is present in the linked list, so our program will return true/Yes.

#### Taking a few more examples:

Input: 4 → 13 → 8 → 20, Value to be searched X = 9.
Output: False

Input: 8 → 9 → 21 → 25, Value to be searched X = 25.
Output: True

Explanation: If the value we are searching is present in the linked list, we will return true/Yes; otherwise, we will return false/No if it is not present.

How should we approach this problem? What is the first thing that comes to mind? Traversing the linked list and checking the given value with the data of every node, right? Yes, that is the correct approach.

Moreover, we can use both iteration and recursion to complete the given task. Let us have a look at both approaches.

### Approach (Iterative)

This approach is going to be iterative.

First, let us think about what should be done to search the given element in the list.

• We will traverse the list, and compare every node’s data with the given element.
• If the element is found, we will return true else, we will return false after the traversal is over.

### Algorithm

• Initialize a node curr and make it point to the head.
• Now, while current is not NULL, traverse the list.
• Compare curr’s data with the given element X.
• If at any point, the curr’s data is equal to X, that means the element is present in the list, and we will return true.
• Keep incrementing curr.
• If the traversal is over and the element is not found, return false.

### Dry Run

#### Code Implementation

```#include <stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct Node
{
int key;
struct Node* next;
};
void push(struct Node** head_ref, int newkey)
{
struct Node* newnode =
(struct Node*)malloc(sizeof(struct Node));

newnode->key = newkey;

}
bool search(struct Node* head, int x)
{
while (current != NULL)
{
if (current->key == x)
return true;
current = current->next;
}
return false;
}
int main()
{
int x = 21;

return 0;
}

```
```#include <bits stdc++.h="">
using namespace std;

class Node
{
public:
int key;
Node* next;
};

{

Node* newnode = new Node();

newnode->key = newkey;

}

{
while (current != NULL)
{
if (current->key == x)
return true;
current = current->next;
}
return false;
}

int main()
{
int x = 21;

return 0;
}
```
```class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}

{

public void push(int newdata)
{

Node newnode = new Node(newdata);

}

public boolean search(Node head, int x)
{
while (current != null)
{
if (current.data == x)
return true;
current = current.next;
}
return false;
}

public static void main(String args[])
{

llist.push(25);
llist.push(13);
llist.push(5);
llist.push(1);

System.out.println("Yes");
else
System.out.println("No");
}
}
```
```class Node:

def __init__(self, data):
self.data = data
self.next = None

def __init__(self):

def push(self, new_data):

new_node = Node(new_data)

def search(self, x):

while current != None:
if current.data == x:
return True

current = current.next

return False

if __name__ == '__main__':

llist.push(25);
llist.push(13);
llist.push(5);
llist.push(1);

if llist.search(13):
print("Yes")
else:
print("No")
```
##### Output

Yes

Time Complexity: O(n), as list traversal is needed.
Space Complexity: O(1), as only temporary variables are being created.

### Approach (Recursive)

The recursive solution is going to be quite similar to the iterative one. We will traverse the given list and compare every node’s data with the given element X. If found, we will return true; else, we will return false.

As this is the recursive approach:

• We will compare the head’s data with the given element.
• If equal, we will return true.
• Else, we will recur for the next node, I.e., head → next.
• If the head becomes NULL, i.e., the list is completely traversed, we will return false as the element is not present in the list.

### Algorithm

• Base Case – If the head is NULL, return false.
• If head → data = X, return true as element has been found.
• Else, we will recur for head → next.
• If the element is not found and the head reaches NULL, i.e., the list traversal is done, then the program will terminate and return false.

### Dry Run

#### Code Implementation

```#include <stdio.h>
#include<stdlib.h>
#include<stdbool.h>

struct Node
{
int key;
struct Node* next;
};
void push(struct Node** head_ref, int newkey)
{
struct Node* newnode =
(struct Node*) malloc(sizeof(struct Node));

newnode->key = newkey;
}
bool search(struct Node* head, int x)
{
return false;
return true;
}
int main()
{
int x = 21;

return 0;
}
```
```#include <bits stdc++.h="">
using namespace std;

struct Node
{
int key;
struct Node* next;
};

void push(struct Node** head_ref, int newkey)
{

struct Node* newnode =
(struct Node*) malloc(sizeof(struct Node));

newnode->key = newkey;
}

bool search(struct Node* head, int x)
{
return false;
return true;
}

int main()
{
int x = 21;

search(head, 13)? cout << "Yes" : cout << "No";
return 0;
}
```
```class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}

{
public void push(int newdata)
{
Node newnode = new Node(newdata);

}
public boolean search(Node head, int x)
{
return false;

return true;

}
public static void main(String args[])
{
llist.push(25);
llist.push(13);
llist.push(5);
llist.push(1);
System.out.println("Yes");
else
System.out.println("No");
}
}
```
```class Node:

def __init__(self, data):
self.data = data
self.next = None

def __init__(self):

def push(self, new_data):

new_node = Node(new_data)

def search(self, x):

return False

return True

return self.search(x)

if __name__ == '__main__':

llist.push(25);
llist.push(13);
llist.push(5);
llist.push(1);

if llist.search(13):
print("Yes")
else:
print("No")
```
##### Output

Yes

Time Complexity: O(n), as list traversal is needed.
[forminator_quiz id=”4603″]

So, in this article, we have tried to explain the most efficient approach to search an element in a Linked List (Iterative and recursive). This is an important question when it comes to coding interviews. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.