您的位置:首页 > 编程语言 > Java开发

【leetcode】Linked List Cycle II

2015-11-04 18:09 405 查看

一、问题描述

Given a linked list, return the node where the cycle begins. If there is no cycle, return 
null
.

Note: Do not modify the linked list.

Follow up:

Can you solve it without using extra space?

二、问题分析

与Linked List Cycle及其相似,同样采用two points的解题思路,不过不同的是我们需要确定环的入口,我们可以这样分析,对于slow和fast指针(slow每次next一次,fast每次next两次),如果有环,那么一定相遇,此时fast指着一定走了两倍的slow的距离,那么与环的大小是否有关呢。我们假定head到环的入口节点的距离为A,两个指针相遇的位置距离环的入口为B,环的长度为C,那么会有如下关系2(A+B)==A+B+nC,我感觉此时应该是nC(因为环可能很小),即fast应该比slow多走了n个环的长度,此时有A+B==nC,而A+B即,head到相遇节点的距离,有A==nC-B,那么此时可以假定有第二个slow2指针,此时slow2和fast都以一个next的距离前进,必然会相遇到环的入口节点。

三、Java AC代码

public ListNode detectCycle(ListNode head) {
if (head==null || head.next==null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if (slow==fast) {
ListNode slow2 = head;
while(slow2!=slow){
slow = slow.next;
slow2 = slow2.next;
}
return slow;
}
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java list