forked from acearth/LeetCodePractice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolutionForCyclicListDetect.java
66 lines (65 loc) · 1.56 KB
/
SolutionForCyclicListDetect.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
66
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class SolutionForCyclicListDetect {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode p = head;
ListNode pp = head;
int breakTag = 0;
while (p.next != null) {
if (pp.next == null) {
break;
}
p = p.next;
pp = pp.next.next;
if (pp == null) {
break;
}
if (p.equals(pp)) {
breakTag = 1;
break;
}
}
if (breakTag == 0) {
return null;
}
p = head;
while (true) {
p = p.next;
if (pp.next.next.equals(pp)) {
p = p.next;
if (p.next.next.equals(p)) {
break;
}
}
pp = pp.next;
if (p.equals(pp)) {
break;
}
}
return p;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(3);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(0);
ListNode l4 = new ListNode(-4);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l2;
SolutionForCyclicListDetect s = new SolutionForCyclicListDetect();
System.out.println(s.detectCycle(l1));
}
}