-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path142.Linked-List-Cycle-II.java
54 lines (45 loc) · 1.11 KB
/
142.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
52
53
54
// https://leetcode.com/problems/linked-list-cycle-ii/
//
// algorithms
// Medium (31.93%)
// Total Accepted: 212,281
// Total Submissions: 664,890
// beats 100.0% of java submissions
/**
* 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 || head.next == null) {
return null;
}
ListNode st = head, nd = head.next;
while (nd != null && st != nd) {
st = st.next;
nd = nd.next;
if (nd != null) {
nd = nd.next;
}
}
if (nd == null) {
return null;
}
int cycleLen = 1;
st = nd.next;
while (st != nd) {
cycleLen++;
st = st.next;
}
st = head;
nd = head;
for (int i = 0; i < cycleLen; i++) {
st = st.next;
}
while (st != nd) {
st = st.next;
nd = nd.next;
}
return st;
}
}