[Python-leetcode142- speed circular linked list pointer 2]

Problem Description:

Given a list, return the first node into the beginning of the chain ring. If chain acyclic, null is returned.

To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.

Description: Do not allow to modify the given list.

Example 1:

Input: head = [3,2,0, -4] , pos = 1
Output: tail connects to node index 1
explained: the list has a ring tail portion connected to a second node.

 

Core: In leetcode141 has been solved to determine whether there is a ring, this title is an upgraded version of the previous question, it is necessary to solve the inlet ring. When the fast and slow pointer Pointer first encounter, so that fast pointer is redirected to the first node, and a predetermined pointer fast and slow pace at this time is the same pointer, when they meet again at this time, that is, the entrance node.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        if head == None or head.next == None:
            return None
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                while head != slow:
                    head = head.next
                    slow = slow.next
                return head
        return None  

result:

 

Guess you like

Origin www.cnblogs.com/xiximayou/p/12337347.html
Recommended