Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
一开始看错了,以为是只要求是否有环路。还是相对比较简单的题目,首先使用快慢指针,一个走两步,一个走一步。如果没环路,快指针会先到。如果有环,两个指针总会相遇。在找到环之后,这两个相遇的指针肯定在环路当中,于是可以在用第三个指针,先走一圈,如何走一圈,很简单。然后再开第四个指针,第三个指针总比第四个指针快一圈,于是同时走,会在环路产生的地方相遇。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
//16:18 -> 16:42 pass
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode n1,n2,n3;
n1 = n2 = head;
if(head==null)
{
return null;
}
while(true)
{
n2 = n2.next;
if(n2!=null)
{
n2 = n2.next;
//whithout this sentence;
if(n2==null)
{
break;
}
}else
{
break;
}
n1 = n1.next;
// there is a cycle
if(n1==n2)
{
n3 = head.next;
n2 = n2.next;
//n2 move a cycle, and the n3 move a cycle too
while(n2!=n1)
{
n2 = n2.next;
n3 = n3.next;
}
//n3 just one cycle faster than n2;
n2 = head;
while(n2!=n3)
{
n3 = n3.next;
n2 = n2.next;
}
return n2;
}
}
return null;
}
}