题目描述:
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
说明:不允许修改给定的链表。
进阶:
你是否可以不用额外空间解决此题?
解答:参考博文此题可看作是一个数学推导题,基本思路是用快慢指针,确定碰撞点,找到碰撞点之后再找出入环位置。具体思路如下:
在上图中,假设慢指针走了n圈,快指针走了m圈,可以列出如下式:
由上述推导,在快慢指针同时到达碰撞点之后,让两个慢指针分别从头结点与碰撞点出发,每次移动相同的步数,最后必然在入环点相遇。
代码如下:
private static ListNode FindJionPoint1(ListNode head) {
ListNode t = head;
ListNode h = head;
if (h == null || h.next == null) return null;
do {
t = t.next;
h = h.next.next;
} while (h != null && h.next != null && t != h);
if (h == null || h.next == null) return null;
//Find Entry Point of the List
ListNode ptr1 = head;
ListNode ptr2 = t;
ListNode prev = null;
while (ptr1 != ptr2) {
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
return ptr1;
}