一、Linked List Cycle I
Linked List Cycle I 只是单纯地确定是否有cycle,可以使用两个指针(fast和slow),fast每次走两步,slow每次走一步。若最后有相交的节点,则有环;若fast节点为null,则无环。也可以使用其他方法,题目并没有要求不能破坏原链表。
二、Linked List Cycle II
题目: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.
解析:相较于I,题目II要求不能修改原链表。
先判断是否有环?若无环返回null。若有环如下图所示,设C点为快慢两指针的相遇点,B为环开始的点,A为head起点。设环的长度为L,当相遇时,存在
Slow | Fast |
AB+BC+xL(走了x圈) | AB+BC+yL(走了y圈) |
【2Slow=Fast】 ---> 【2(AB+BC+xL)=AB+BC+yL】 ---> 【AB+BC=mL(y-2x简化为m)】。在相遇点C,已经走了BC段,那么从C点出发再走AB段的距离一定能到达B点。因此设置指针res从A点出发,slow从C点出发,两者相遇的位置一定是所求的环起始点!!!
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null) return null;
ListNode slow=head,fast=head;//设置一快一慢两个指针遍历链表
while(fast!=null){
slow=slow.next;
if(fast.next==null) break;
else fast=fast.next.next;
if(slow == fast) break;
}
if(slow==fast){//如果相遇,在设置一个从头出发的指针。和从相遇点出发的slow同时走,再次相遇点即为所求。
ListNode res=head;
while(res!=slow){
res=res.next;
slow=slow.next;
}
return res;
}else
return null;
}
}