[LeetCode] Linked List CycleII

原问题如下:

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?

给一个Linked List,返回cycle 开始的ListNode。如果没有cycle,则返回null。

问题分析:

一、先给出一个在stackoverflow上看到的很好的思路detecting the start of a loop in a singly linked link list? 

Step1: Proceed in the usual way u'll use to find the loop. ie. Have two pointers, increment one in single step and other in two steps, If they both meet in sometime, there is a loop.

用Linked List Cycle那一题的方法判断是不是有loop,如果没有返回null吧。假如两个pointer在某个位置相遇了,指针留在那别走!Step2有用!

Step2: Freeze one pointer where it was and increment the other pointer in one step counting the steps u make and when they both meet again, the count will give u the length of the loop.(This is same as counting the number of elements in a circular link list.)

用慢指针走一圈loop,量出loop的长度L。

Step3: Reset both pointers to the start of the link list, increment one pointer to the length of loop times and then start the second pointer. increment both pointers in one step and when they meet again, it'll be the start of the loop. (This is same as finding the nth element from the end of the link list.)

把两个Pointer都拿回Linked List的Starting Point,把其中一个Pointer(记作A)移动L个位置。然后两个Pointer都一步一步地往前移动,他们的相遇点就是loop的起点了。

(简单说来就是Linked List总长度是M,Loop长度是L。假设List起点到Loop起点的距离N = M - L,也就是Step3中Pointer A的起点位置到Loop起点的距离。但我们不知道Loop总长度L,也就不知道N是多少;但我们知道List起点到Loop起点的距离是N,Pointer A到Loop起点的距离也是N,但两个Pointer在不同的次元(一个在Loop外,一个在Loop内),所以当他们相遇时,相遇的点就是Loop的Starting Point了。)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值