1039. Search in Linked List

You are given the head of a singly linked list and an integer key.

Return true if the key exists in the linked list, otherwise return false.

Example 1:

Input: head = [1, 2, 3, 4], key = 3

Output: true

Explanation: The linked list is 1 → 2 → 3 → 4. The key 3 is present in the list.

Example 2:

Input: head = [7, 8, 9, 10, 11], key = 5

Output: false

Explanation: The key 5 is not present in the list.

Now Your Turn!

Pick the correct output for the given input

Input: head = [42], key = 42

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the linked list is in the range 1 <= n <= 10⁵.
  • The value of each node is in the range 1 <= Node.val <= 10⁵.
  • 1 <= key <= 10⁵
0
/*Defination of ListNode
class ListNode {
public:
int val;
ListNode* next;
 
ListNode(int value) : val(value), next(nullptr) {}
 
~ListNode() {
delete next;
}
};
*/
 
 
class Solution {
public:
bool searchKey(ListNode* head, int key) {
// Your code goes here
}
};
Test Case

Input:

Head
Key