Linked List Cycle II
Solution
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
// 2
Set<ListNode> set = new HashSet<>();
ListNode current = head;
while (current != null) {
if (set.contains(current)) {
return current;
} else {
set.add(current);
}
current = current.next;
}
return null;
}
}Last updated