题目
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Notice that you should not modify the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
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.
Constraints:
- The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
- pos is -1 or a valid index in the linked-list.
解法一,用set存储对象
把每个节点存储到不可重复集合set中,判断是否存在即可。但是存储比较多,速度就会稍微慢一点。
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class LinkedListCycleII:
def detectCycle(self, head: ListNode) -> ListNode:
nodeSet = set()
while head :
if head in nodeSet:
return head
nodeSet.add(head)
head = head.next
return Non
解法二,快慢指针
定义两个指针慢和快。 两者都是从头节点开始的,快是慢的两倍。 如果到达末尾,则表示没有周期,否则最终它将最终赶上周期中某个地方的慢速指针。
假设从第一个节点到开始循环的节点的距离为A,并且慢速指针行进为A + B。 快速指针必须经过2A + 2B才能赶上。 周期的大小为N。完整的周期也是相交的慢速指针经过的时间比慢速指针经过了多少。
A + B + N = 2A + 2B
N = A + B
根据我们的计算,慢速指针在遇到快速指针时会精确地经过整个周期,并且由于它最初在循环开始之前就经过了A,因此它必须经过A才能到达循环开始的点! 我们可以在头节点处启动另一个慢速指针,然后移动两个指针,直到它们在循环开始时相遇为止。
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def detectCycleWithTwoPointer(self, head: ListNode) -> ListNode:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
slow2 = head
while slow2 != slow:
slow = slow.next
slow2 = slow2.next
return slow
return None