基本功,很好的参考:点击打开链接
/**
* 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 fn = head.next, sn = head;
while (fn != sn) {
if (fn == null || fn.next == null) {
return null;
}
fn = fn.next.next;
sn = sn.next;
}
while(head != sn.next) {
head = head.next;
sn = sn.next;
}
return head;
}
}