给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
/**
* 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 || head.next.next==null)//排除特殊情况
return null;
ListNode fast = head;
ListNode slow = head;
while(fast.next!=null && fast.next.next!=null) {
fast = fast.next.next;
slow = slow.next;
if(fast==slow)
break;
}
if(fast!=slow)
return null;
fast = head;
while(fast!=slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}