LeetCode OJ 142. Linked List Cycle II

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?

这个题还是蛮考验数学推理的,不过在前一个题的基础上还是能推出结果的。这是英文一段解释,非常有帮助。

First Step: Assume the first pointer runs from head at a speed of 1-by-1 step, as S, and the second pointer runs at a speed of 2-by-2 step, as 2S, then two pointers will meet at MEET-POINT, using the same time. Define outer loop is A, the distance from CIRCLE-START-POINT to MEET-POINT is B, and the distance from MEET-POINT to CIRCLE-START-POINT is C (Apparently, C=loop-B), then (n*loop+a+b)/2S = (a+b)/S, n=1,2,3,4,5,....

Converting that equation can get A/S=nloop/S-B/S. Since C=loop-B, get A/S = ((n-1)loop+C)/S.

That means, as second step, assuming a pointer running from head and another pointer running from MEET-POINT both at a speed S will meet at CIRCLE-START-POINT;

代码如下:

 1 public class Solution {
 2     public ListNode detectCycle(ListNode head) {
 3         if(head==null || head.next==null) return null;
 4         ListNode pointer1 = head;
 5         ListNode pointer2 = head;
 6         
 7         while(pointer1!=null && pointer2!=null){
 8             pointer1 = pointer1.next;
 9             if(pointer2.next==null) return null;
10             pointer2 = pointer2.next.next;
11             
12             if(pointer1==pointer2) break;
13         }
14         if(pointer1==null || pointer2==null) return null;
15         
16         pointer1 = head;
17         while(pointer1 != pointer2){
18             pointer1 = pointer1.next;
19             pointer2 = pointer2.next;
20         }
21         return pointer1;
22     }
23 }

 

转载于:https://www.cnblogs.com/liujinhong/p/5407055.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值