Linked List Cycle II LeetCode solution in Java

1
public class Solution {
2
public ListNode detectCycle(ListNode head) {
3
if (head == null) return null;
4
ListNode tortoise = head;
5
ListNode hare = new ListNode();
6
hare.next = head.next;
7
while (hare != null && hare.next != null && hare != tortoise) {
8
tortoise = tortoise.next;
9
hare = hare.next.next;
10
}
11
if (hare == null || hare.next == null) return null;
12
tortoise = head;
13
while (tortoise != hare) {
14
tortoise = tortoise.next;
15
hare = hare.next;
16
}
17
return hare;
18
}
19
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0