这道题在1的基础上要我们找到环的起点。 由于环的起点不一定就是链表的起点,所以我们设链表起点到环起点距离为x,慢指针在环中走了y,慢指针走到环起点距离为z。
那么慢指针走了x+y,快指针走了x+y+z+y。 快指针走的距离是慢指针的两倍,因而得到x=z。 即快慢指针第一次相遇的时候链表起点到环起点的距离等于相遇节点到环起点的距离。 因而两个while即可。
/**
* 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 res =null;
boolean is=false;
if( head==null )
{
return res;
}
ListNode st1=head,st2=head;
while( st1.next!=null && st2.next!=null && st2.next.next!=null )
{
st1=st1.next;
st2=st2.next.next;
if( st1==st2 )
{
res=st1;
break;
}
}
if(res==null)
{
return res;
}
st1=head;
while(st1!=st2)
{
st1=st1.next;
st2=st2.next;
}
return st1;
}
}
本文详细介绍了如何在已知链表存在环的情况下,通过快慢指针法找到环的起点。通过设置慢指针和快指针,利用它们速度差的特点,在首次相遇时计算出从链表起点到环起点的距离,进而实现定位。
258

被折叠的 条评论
为什么被折叠?



