leetcode11.Linked List Cycle II

来源:互联网 发布:java byte类型 编辑:程序博客网 时间:2024/05/22 00:51

问题比之前的那个问题麻烦了点

iven 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?

思路:依旧快慢指针,当相遇之后,慢指针退回到头节点处,俩指针通速度前进至相遇

java:

package leetcode9.LinkHasOrNotCycle;class ListNode{int val;ListNode next;ListNode(int x){val=x;next=null;}}public class Solution_II {public ListNode detectCycle(ListNode head){if(head==null){return null;}ListNode fast=head;ListNode slow=head;while(fast.next!=null){fast=fast.next.next;if(fast==null){return null;}slow=slow.next;if(fast==slow){    slow = head;                while (fast != slow) {                   fast = fast.next;                   slow = slow.next;              }                                    return fast;                }}return null;}}


证明原理:

设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。slow和fast的速度分别是qs,qf。

第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。

因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)

如果圈很小,而a很长,那么b的长度就会是绕圈几周了,但是结果也是一样成立的。

证明来源于:http://blog.csdn.net/kenden23/article/details/13871699

证明来源处有附图,可参考
0 0
原创粉丝点击