Search an Element in Linked List
- Shreyas Naphad
- Jun 5, 2024
- 1 min read
In this article, we will solve the problem of searching for an element in a linked list.
Problem Statement: We are given the head of a singly linked list and an integer value. Our task is to determine if the integer value exists in the linked list.
Example:
Input: list = [1 -> 2 -> 3 -> 4 -> 5], value = 3Output: true
Input: list = [1 -> 2 -> 3 -> 4 -> 5], value = 6Output: false
Solution:
To solve this problem, we will follow these steps:
Steps to Solve:
1. Initialize a Current Pointer:
o Start with the head of the linked list.
2. Traverse the Linked List:
o Iterate through the linked list nodes one by one.
o Compare the current node's value with the target value.
3. Check for Value:
o If a node with the target value is found, return true.
o If the end of the list is reached without finding the target value, return false.
Time Complexity: O(N)
Space Complexity: O(1)
Comments