-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution142.java
More file actions
executable file
·47 lines (45 loc) · 1.12 KB
/
Copy pathSolution142.java
File metadata and controls
executable file
·47 lines (45 loc) · 1.12 KB
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
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
class Solution142 {
public ListNode detectCycle(ListNode head) {
ListNode p = head;
HashMap<ListNode, Integer> visited = new HashMap<>();
int index = 0;
while (p != null) {
if (visited.containsKey(p)) return p;
visited.put(p, index);
p = p.next;
}
return p;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null) {
fast = fast.next;
if (fast != null) fast = fast.next;
else return null;
if (slow != null) slow = slow.next;
if (slow == fast) {
ListNode res = head;
while (res != slow) {
res = res.next;
slow = slow.next;
}
return res;
}
}
return null;
}
}