一个链表可能有一个环,返回这个环的起始位置,如无环,返回null
题解:
利用快慢指针来求解
设链表head到环的起始位置之间的距离为A,slow和fast在环的某个位置P相遇
设环的起始位置到相遇的位置P之间的距离为B,相遇的位置P到环的起始位置之间的距离为C。
那么,2*(A+B) = A+2*B + C
因为fast的速度是slow的2倍
所以A = C,即当slow和fast相遇时,设置一个slow2,slow2到P的距离等于slow到P的距离
/**
* 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 slow = head,fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
ListNode slow2 = head;
while(slow2 != slow){
slow = slow.next;
slow2 = slow2.next;
}
return slow;
}
}
return null;
}
}