https://oj.leetcode.com/problems/linked-list-cycle-ii/
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
这题其实是固定做法,首先先用Linked List Cycle的做法找到第一个相交点,
第二,然后把慢指针返回头指针,然后快慢指针都一步步走next,然后再找到相交点,然后就算是找到了。
给出代码:
public ListNode detectCycle(ListNode head) {
ListNode one_step = head, two_step = head;
while(one_step != null && two_step != null){
if(two_step.next == null || one_step.next == null){
return null;
}
one_step = one_step.next;
two_step = two_step.next.next;
if(one_step == two_step)
break;
}
if(one_step == null || two_step == null)
return null;
one_step = head;
while(one_step != two_step){
one_step = one_step.next;
two_step = two_step.next;
}
return one_step;
}
2018-01-21 Update:
果然不出我所料,上一次我只是记忆着答案,并没有真正的去理解它。所以我这一次思考了一下。得到了下面的解释:
假设存在环。那么假设从head到环的起点的长度为m,环自身的长度为n。第一次oneStep和twoStep相遇的时候oneStep走了k步。那么我们可以得到下面这条式子: (k - m) % n == (2 * k - m) % n。 根据这条式子我们可以知道k是可以被n整除的。所以此时twoStep所处的位置可以用-m % n表示。所以当oneStep再一次走完m这个长度到达环的起点的时候,twoStep所处的位置也会变成如下表达: (-m + m) % n = 0 % n。 也就是环的起点,所以他们这时会恰好在环的起点相遇,而他们第二次相遇的点便是环的起点。
本文讨论了如何在给定的链表中找出循环的起始节点,包括使用快慢指针的方法来定位相交点,以及通过将慢指针重新定位至链表头部并同时移动两个指针来确定起始点。
480

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



