-
-
Notifications
You must be signed in to change notification settings - Fork 419
/
linked-list-cycle-ii.java
51 lines (40 loc) · 1.08 KB
/
linked-list-cycle-ii.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 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) {
if(head == null){
return null;
}
ListNode slowPtr = isCycleExists(head);
ListNode fastPtr = head;
if(slowPtr != null){
while(fastPtr != slowPtr){
fastPtr = fastPtr.next;
slowPtr = slowPtr.next;
}
return slowPtr;
}
return null;
}
public ListNode isCycleExists(ListNode head){
ListNode currentHead = head;
ListNode slowPtr = head;
ListNode fastPtr = head;
while (fastPtr != null && fastPtr.next != null) {
slowPtr = slowPtr.next;
fastPtr = fastPtr.next.next;
if (slowPtr == fastPtr)
return slowPtr;
}
return null;
}
}