[3,2,0,-4]
1
Expect:tail connects to node index 1
Actually:tail connects to node index 3
思路是判断有环否。
然后计算环中节点数(长度)n
然后fast,slow从头开始,slow每次移动一个节点。fast每次移动n个节点。当它们再次相遇,同时指向的节点为环的第一个节点。
/**
* 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) {
int count = 1, isCycle = 0;
ListNode s = head, f = head;
if (head == null || head.next == null) {
return null;
}
while (f.next.next != null && s.next != null) {
f = f.next.next;
s = s.next;
if (f == s) {
isCycle = 1;
break;
}
} //if linked list is Cycle linked list, isCycle is 1
if (isCycle == 1) { //Cycle linked list
f = f.next;
while (f != s) {
count++;
f = f.next;
} // get the length of cycle
ListNode s1 = head;
ListNode f1 = head;
for (int i = 0;i < count; i++) {
f1 = f1.next;
}
while (f1 != s1) {
s1 = s1.next;
for (int i = 0;i < count; i++) {
f1 = f1.next;
}
}
return s1;
}
return null;
}
}