18-142. Linked List Cycle II

题目描述:

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?

代码实现:

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def detectCycle(self, head):
 9         """
10         :type head: ListNode
11         :rtype: ListNode
12         """
13         try:
14             fast = head.next
15             slow = head
16             while fast is not slow:
17                 fast = fast.next.next
18                 slow = slow.next
19         except:
20             # if there is an exception, we reach the end and there is no cycle
21             return None
22 
23         # since fast starts at head.next, we need to move slow one step forward
24         slow = slow.next
25         while head is not slow:
26             head = head.next
27             slow = slow.next
28 
29         return head

参考资料:https://leetcode.com/problems/linked-list-cycle-ii/discuss/44783/Share-my-python-solution-with-detailed-explanation

原文地址:https://www.cnblogs.com/tbgatgb/p/10992375.html