[LeetCode] Linked List CycleII

来源:互联网 发布:mac safari 扩展 编辑:程序博客网 时间:2024/05/18 00:02

原问题如下:

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了。)


0 0
原创粉丝点击