In this article, we will learn to how to search an element in a linked-list. It is a very simple program which is generally asked in the interview.

For example:

Here we will see two methods to find the element, iteration, and recursion.

Iteration method

Step to find the element in a given linked list
  • Assign the address of the first node to a temporary node pointer (Tmp).
  • Traverse the linked list until node pointer (Tmp != NULL).
  • Check the element in every iteration of the linked-list, if the given element is matched with tmp->iData then return TRUE else return FALSE.

Source Code

 

Example code to search an element in a given linked list using iterative

In a given example code, first, we will create a linked list as per the choice. when the linked list has created then we will search the element in a created linked list using the iterative method.

OutPut 1:

OutPut 2:

Recursion Method:

Steps to search the element using the recursive method
  • If head pointer (pNode->iData ) is NULL, return FALSE.
  • If current node element (pNode->iData ) is same as iElement, return TRUE.
  • Else call return SearchTheElement ( pNode->pNextNode,iElement ).

Source Code

Example code to search an element in a given linked list using recursion

In a given example code, first, we will create a linked list as per the choice. when the linked list has created then we will search the element in a created linked list using the recursive method.

OutPut 1:

OutPut 2: