Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it without using extra space?
Reference Answer
思路分析
这个求单链表中的环的起始点是之前那个判断单链表中是否有环的延伸,还是要设快慢指针,不过这次要记录两个指针相遇的位置,当两个指针相遇了后,让其一指针从链表头开始,一步两步,一步一步似爪牙,似魔鬼的步伐。。。哈哈,打住打住。。。此时再相遇的位置就是链表中环的起始位置。代码如下:
链表环补充
扩展问题:
在网上搜集了一下这个问题相关的一些问题,思路开阔了不少,总结如下:
-
环的长度是多少?
-
如何找到环中第一个节点(即Linked List Cycle II)?
-
如何将有环的链表变成单链表(解除环)?
-
如何判断两个单链表是否有交点?如何找到第一个相交的节点?
首先我们看下面这张图:
设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。slow和fast的速度分别是qs,qf。
下面我们来挨个问题分析。
-
方法一(网上都是这个答案):
第一次相遇后,让slow,fast继续走,记录到下次相遇时循环了几次。因为当fast第二次到达Z点时,fast走了一圈,slow走了半圈,而当fast第三次到达Z点时,fast走了两圈,slow走了一圈,正好还在Z点相遇。
方法二:
第一次相遇后,让fast停着不走了,slow继续走,记录到下次相遇时循环了几次。
方法三(最简单):
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
我们发现L=b+c=a+b,也就是说,从一开始到二者第一次相遇,循环的次数就等于环的长度。
-
我们已经得到了结论a=c,那么让两个指针分别从X和Z开始走,每次走一步,那么正好会在Y相遇!也就是环的第一个节点。
不用担心两者永远不能相遇,因为快指针每次都比慢指针快1,所以不管链表是否为偶数或奇数个节点,不影响两者相遇。
代码如下:
Code
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next or not head.next.next:
return None
fast = head
slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if slow == fast:
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
return None
Note
- 依旧链表环,依旧不会做,重点找结论啊~~~
参考文献
[1] http://www.cnblogs.com/grandyang/p/4137302.html
[2] http://www.cnblogs.com/hiddenfox/p/3408931.html