-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathSolution.java
65 lines (53 loc) · 1.25 KB
/
Solution.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package nine;
/**
* @author dmrfcoder
* @date 2019/4/10
*/
/**
* 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 fast, slow;
fast = slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
break;
}
}
if (fast.next == null || fast.next.next == null) {
return null;
}
fast = head;
while (fast != null && slow != null) {
if (fast == slow) {
return fast;
}
fast = fast.next;
slow = slow.next;
}
return null;
}
public static void main(String[] args){
ListNode head=new ListNode(1);
ListNode node2=new ListNode(2);
head.next=node2;
node2.next=head;
Solution solution=new Solution();
ListNode res=solution.detectCycle(head);
System.out.println(res.val);
}
}