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.

Suppose the linked list is:

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; 
  
    newnode->next = (*head_ref); 
    (*head_ref) = newnode; 
} 
bool search(struct Node* head, int x) 
{ 
    struct Node* current = head; 
    while (current != NULL) 
    { 
        if (current->key == x) 
            return true; 
        current = current->next; 
    } 
    return false; 
} 
int main() 
{ 
    struct Node* head = NULL; 
    int x = 21; 
    push(&head, 25); 
    push(&head, 13); 
    push(&head, 5); 
    push(&head, 1); 
  
    search(head, 13)? printf("Yes") : printf("No"); 
    return 0; 
} 

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

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

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

    Node* newnode = new Node();
  

    newnode->key = newkey; 
  

    newnode->next = (*head_ref); 

    (*head_ref) = newnode; 
} 

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

int main() 
{ 
    Node* head = NULL; 
    int x = 21; 
    push(&head, 25); 
    push(&head, 13); 
    push(&head, 5); 
    push(&head, 1); 
  
    search(head, 13)? cout<<"Yes" : cout<<"No"; 
    return 0; 
} 
class Node
{
    int data;
    Node next;
    Node(int d)
    {
        data = d;
        next = null;
    }
}

public class LinkedList
{
    Node head; 

    public void push(int newdata)
    {

        Node newnode = new Node(newdata);

        newnode.next = head;

        head = newnode;
    }

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

    public static void main(String args[])
    {


        LinkedList llist = new LinkedList();

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

        if (llist.search(llist.head, 13))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
class Node:
	
	def __init__(self, data):
		self.data = data 
		self.next = None 

class LinkedList:
	def __init__(self):
		self.head = None

	def push(self, new_data):
	
		new_node = Node(new_data)
		new_node.next = self.head
		self.head = new_node

	def search(self, x):

		current = self.head

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


if __name__ == '__main__':

	llist = LinkedList()

	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; 
    newnode->next = (*head_ref); 
    (*head_ref) = newnode; 
} 
bool search(struct Node* head, int x) 
{ 
    if (head == NULL) 
        return false; 
    if (head->key == x) 
        return true; 
    return search(head->next, x); 
} 
int main() 
{
    struct Node* head = NULL; 
    int x = 21; 
    push(&head, 25); 
    push(&head, 13); 
    push(&head, 5); 
    push(&head, 1);  
  
    search(head, 13)? printf("Yes") : printf("No"); 
    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; 
    newnode->next = (*head_ref); 
    (*head_ref) = newnode; 
} 

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

int main() 
{
    struct Node* head = NULL; 
    int x = 21; 
    push(&head, 25); 
    push(&head, 13); 
    push(&head, 5); 
    push(&head, 1);  
  
    search(head, 13)? cout << "Yes" : cout << "No"; 
    return 0; 
} 
class Node
{
    int data;
    Node next;
    Node(int d)
    {
        data = d;
        next = null;
    }
}
  
public class LinkedList
{
    Node head; 
    public void push(int newdata)
    {
        Node newnode = new Node(newdata);

        newnode.next = head;

        head = newnode;
    }
    public boolean search(Node head, int x)
    {
        if (head == null)
            return false;

        if (head.data == x)
            return true;

        return search(head.next, x);
    }
    public static void main(String args[])
    {
        LinkedList llist = new LinkedList();
        llist.push(25);
        llist.push(13);
        llist.push(5);
        llist.push(1);
        if (llist.search(llist.head, 13))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
class Node:
    
    def __init__(self, data):
        self.data = data 
        self.next = None 

class LinkedList:
    def __init__(self):
        self.head = None

    def push(self, new_data):
    
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node

    def search(self, x):

        if self.head == None:
            return False
        
        if self.head.data == x:
            return True
        
        self.head = self.head.next
        return self.search(x)
        


if __name__ == '__main__':

    llist = LinkedList()

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *