Solution: Search in a Singly Linked List

Let’s solve the Search in a Singly Linked List problem.

Statement

Given the head of a singly linked list, search for a specific value. If the value is found, return TRUE; otherwise, return FALSE.

Constraints:

Let n be the number of nodes in a linked list.

  • 00 \leq n500\leq 500

  • 5000-5000 \leq Node.data, value5000\leq 5000

Solution 1: Iterative approach

The solution takes an iterative approach toward the problem. It starts by positioning a pointer at the first node of the list. As long as the list has elements, we check if the data in the current node matches the value being searched for. If a match is found, the algorithm returns True, indicating that the value has been found within the list. If no match is found after checking all nodes, the algorithm returns False, indicating that the value is not present within the list.

Let’s look at the illustration below to better understand the solution:

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