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.

We'll cover the following

Problem Statement

Itâ€™s time to figure out how to implement another favorite 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 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 value to be searched.

Output

true if the value is found, false otherwise.

Sample Input

Linkedlist = 5->90->10->4
Value = 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 EduLinkedListNode and EduLinkedList classes implemented in the previous lessons are available to you.

Test your code against our cases and see if you can pass them. You have access to isEmpty(), getHead(),
printList(), insertAtHead() and insertAtTail() functions of LinkedList.

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

If you get stuck, you can always refer to the solution explained in the next lesson

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