题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
分析:
个人觉得这题的原理没有必要一定用数学公式深究,记住这个方法就可以,因为对别的题并不具备推广性,有兴趣的话网上的数学推导也有很多。
1. 首先利用快慢指针的方法判断链表是否有环。
2. 如果链表没环,直接返回null。如果有环,仍然用两个指针,第一个指向链表的头节点,另一个指向快慢指针相遇的节点,两个链表每次走一步,它们相遇的点就是环的入口。
Java代码实现:
/**
* 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;
ListNode slow = head;
while(fast!=null)
{
slow = slow.next;
if(fast.next!=null)
fast = fast.next.next;
else
return null;
if(slow==fast)
break;
}
if(fast==null)
return null;
ListNode node = head;
while(node!=slow)
{
node = node.next;
slow = slow.next;
}
return node;
}
}