Description:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
问题描述:
给定一条链表,判断是否有环,函数返回环开始的第一个结点(也就是环的入口处)
解法一:
思路:
这个问题算是之前判断链表是否有环问题的一个拓展。解决这个问题的思路分为两步,第一步是个追击问题(找到快慢指针第一次相遇的地方),第二步是个相遇问题(找到链表环的入口处)。
现在需要设定三个指针,一个快(fast)指针,一个慢(slow)指针,一个start指针。设环形链表的长度为r。
追击问题: 快指针走2k步时,慢指针走了k步,由于2k-k= nr,那么当k = r时,快慢指针第一次相遇。假设次数慢指针距离环的入口处为m , start指针距离环的入口处为s .
相遇问题:慢指针一次走一步,start指针也是一次走一步,由于s + m = nr , 所以两个指针一定会在环的入口处相遇。否则链表无环。
Code:
/**
* 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) {
if(head == null || head.next == null)
return null;
ListNode fast = head , slow = head , start = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
while(slow != start){
slow = slow.next;
start = start.next;
}
return start;
}
}
return null;
}
}