您的位置:首页 > 其它

Linked List Cycle II

2015-02-24 14:25 274 查看
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, return
null
.

Follow up:

Can you solve it without using extra space?

public ListNode detectCycle(ListNode head)
这题其实是固定做法,首先先用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。 也就是环的起点,所以他们这时会恰好在环的起点相遇,而他们第二次相遇的点便是环的起点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: