Occurence of an integer in a Linked List
JavaView on GFG
Time: O(n)
Space: O(1)
Advertisement
Intuition
Count occurrences of a target value in linked list. Linear scan.
Algorithm
- 1Traverse list, increment counter each time node.val == target.
Common Pitfalls
- •Simple O(n) traversal. Handle empty list (return 0).
Occurence of an integer in a Linked List.java
Java
// Approach: Traverse list and count nodes with matching value.
// Time: O(n) Space: O(1)
class Node {
int data;
Node next;
Node(int key) {
data = key;
next = null;
}
}
class Solution {
public static int count(Node head, int key) {
int count = 0;
Node temp = head;
while (temp != null) {
if (temp.data == key) {
count++;
}
temp = temp.next;
}
return count;
}
}Advertisement
Was this solution helpful?