Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
解题思路:快慢指针,从起点走,快指针步长为2,慢指针步长为1,假设有环,相遇时,快指针走了x+k+my,其中m为相遇前走的圈数,慢指针走了x+k,由于步长关系很容易得出x+k+my = 2*(x+k),即my = x+k,此时快指针从起点开始走,慢指针从相遇点走,当快指针走到环的入口时,慢指针走了my-k,而m>=1,因此慢指针也会走到入口,再次相遇
考虑特殊情况:
无环,quik遇到空
/**
* 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) {
ListNode quik, slow;
int cnt = 0;
quik = head;
slow = head;
if(head == null || head.next == null){
return null;
}
while(true){
if(quik == slow){
cnt++;
if(cnt == 2){
quik = head;
continue;
}
}
if(cnt == 3){
break;
}
if(cnt > 1){
//当处于第二轮的时候,同为慢指针
slow = slow.next;
quik = quik.next;
}else{
if(quik == null || quik.next == null){
return null;
}
//当处于快慢指针时
slow = slow.next;
quik = quik.next.next;
}
}
return slow;
}
}