detectCycleWithHashSet<T> function
Detects cycle using hash set approach (alternative method)
head - The head of the linked list to check
Returns true if a cycle exists, false otherwise
Time Complexity: O(n) where n is the length of the list Space Complexity: O(n) due to hash set
Implementation
bool detectCycleWithHashSet<T>(LinkedListNode<T>? head) {
Set<LinkedListNode<T>> visited = {};
LinkedListNode<T>? current = head;
while (current != null) {
if (visited.contains(current)) {
return true;
}
visited.add(current);
current = current.next;
}
return false;
}