问题描述:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
思考:
参考了网上的方法,判断一个单向链表是否有环,如果没有返回空,如果有返回这个环的开始处,也就是和前面直线的焦点。
画出图:
从开始的节点分别放慢指针和快指针两个指针,快的每次走两步,慢的每次走一步。
类似时针分针,如果链表有环,两个指针一定会在环中相遇,此时即可推断:
2s = nc+s,
s=a+x,
=> a+x=nc,
a=nc-x,
a=(n-1)c+c-x其中n-1为整数圈数,这个意思是当两个指针相遇的时候,把快指针放回头节点,慢指针在原处,快指针每次就只走一步了,此时快指针走到环开始的地方时,慢指针走了剩余的半圈加(n-1)个整圈,以此找出环开始处。
代码(java):
public class LinkedListCycleII {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode detectCycle(ListNode head) {
ListNode slow,fast;
//只有一个节点或者就没有
if(head == null || head.next == null){
return null;
}
//正式开始
slow = head;
fast = head;
while(true){
if(fast == null || fast.next == null){
return null;
}
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
break;
}
}
slow = head;
while(true){
if(slow == fast){
break;
}
slow = slow.next;
fast = fast.next;
}
return slow;
}
}