Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: 10 Dec, 2020

Search in a Linked List

Easy
Asked in companies
Tata Consultancy Services (TCS)ONEPERCENT SOFTWARE (OPC) PRIVATE LIMITED

Problem statement

You are given a Singly Linked List of integers with a head pointer. Every node of the Linked List has a value written on it.


A sample Linked List:

Sample Linked List

Now you have been given an integer value, 'K'. Your task is to check whether a node with a value equal to 'K' exists in the given linked list. Return 1 if node exists else return 0.

Input Format:
The first line of the input contains space-separated integers denoting the values of nodes of the Linked List. 

The Linked List is terminated with -1. Hence, -1 is never a node value of the Linked List.

The second line contains a single integer 'K', which is desired to be checked in the Linked List.
Output Format:
The only line contains 1 if the desired value 'K' exists in the Linked List, otherwise, print 0.
Note:
You do not need to print anything; it has already been handled. Just implement the given function.

Approaches

01 Approach

Let's try to build a recursive solution to this problem

The recursive function has three cases:

  1. The Head is NULL(it means that we have reached the end of the linked list without finding value ‘K’ that means the particular value is not present in the Linked List. So, in this case, we will return 0 as our answer).
  2. The Head is Not NULL, and the value of the head is equal to the desired value ‘K’ we will return 1 in this case as we found the desired value in the Linked List.
  3. The Head is Not NULL, and the current value is not equal to the desired value ‘K’, so it will recur to the next node of the head and undergo the same process there.