Challenge: Search in a Singly Linked List

This lesson explains how searching is done in a singly linked list. There is also a coding exercise to test your concepts.

Problem Statement

It’s time to figure out how to implement another popular linked list function: search

To search for a specific value in a linked list, there is no other approach but to traverse the whole list until we find the desired value.

In that sense, the search operation in linked lists is similar to the linear search in normal lists or arrays - all of them take O(n) amount of time.

The search algorithm in a linked list can be generalized to the following steps:

  1. Start from the head node.
  2. Traverse the list till you either find a node with the given value or you reach the end node which will indicate that the given node doesn’t exist in the list.

Input

A linked list and an integer to be searched.

Output

True if the integer is found. False otherwise.

Sample Input

Linked List = 5->90->10->4  
Integer = 4

Sample Output

True

Coding Exercise

If you know how to insert an element in a list, then searching for an item will not be that difficult for you.

Now, based on the steps mentioned above, we have designed a simple coding exercise for your practice.

The Node and LinkedList classes are available to you.

Try to solve this exercise on your own. There are hints to help you along the way.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.