题目内容
https://leetcode-cn.com/problems/linked-list-cycle-ii/
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
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.
题目思路
这道题目的思路在于如何找到位置。英文版和中文版LC的判定不太一样,但是不影响这道题目的关键。在快慢指针相遇后,这时候从头结点开始遍历,同时移动慢指针。当两个指针相遇的时候, 就是开始循环的位置。
程序代码
# 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:
return False
p,q=head,head
while q and q.next:
p=p.next
q=q.next.next
if p==q:
t=head
while t!=p:
t=t.next
p=p.next
return t
return False