Last Updated: 3 Jun, 2017

Find a Node in Linked List

Easy
Asked in companies
Hewlett Packard EnterpriseCadence Design SystemsRTDS

Problem statement

You have been given a singly linked list of integers. Write a function that returns the index/position of integer data denoted by 'N' (if it exists). Return -1 otherwise.

Note :
Assume that the Indexing for the singly linked list always starts from 0.
Input format :
The first line contains an Integer 'T' which denotes the number of test cases. 

The first line of each test case or query contains the elements of the singly linked list separated by a single space. 

The second line contains the integer value 'N'. It denotes the data to be searched in the given singly linked list.
Remember/Consider :
While specifying the list elements for input, -1 indicates the end of the singly linked list and hence -1 would never be a list element.
Output format :
For each test case, return the index/position of 'N' in the singly linked list. Return -1, otherwise.

Output for every test case will be printed in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
 Constraints :
1 <= T <= 10^2
0 <= M <= 10^5

Where 'M' is the size of the singly linked list.

Time Limit: 1 sec

Approaches

01 Approach

The steps are as follows:

 

  1. If the head is null, return -1 since an empty list will obviously not contain the element that we need to look for.
  2. Check whether the head’s data is equal to the element we want to search. Return 0 if it is.
  3. Then recurse on the next node from the head and get its answer.
  4. If the answer from the recursive call is -1, your answer is also -1 since you already check the head’s data.
  5. If the recursive call’s answer is non zero then add one to it and return because the list we had sent in the recursive call is shifted by one.

02 Approach

The steps are as follows:

 

  1. Iterate through the linked list by maintaining a ‘CURRENT’ node variable to store the reference to the current node and a ‘POS’ variable to store the position of the current node.
  2. Check whether ‘CURRENT’ node’s data is equal to the element we were looking for, if yes return the value of ‘POS’, otherwise repeat this step by increasing the value of ‘POS’ by 1 and moving ‘CURRENT’ to its next node.
  3. If ‘CURRENT’ becomes equal to null, just return -1 since we didn’t find the element we were looking for.