The ingress node of the list to prove safety ring offer- - list -python ***

Title Description

To a linked list, wherein if the ring comprises, find the entry ring node list, otherwise, outputs null.

Thinking

The first step, to find sink ring relative speed with two pointers. Respectively slowfastpoint to the head of the list, sloweach time step, fasteach take two steps, until the fast == slowfound phase sink in the ring.
The second step, to find the inlet ring. When fast == slow, it is assumed slowthrough the x nodes, the fastthrough 2x nodes. Provided there are n nodes in the ring, since the fastratio of slowmulti-walk around (n nodes), it is the equation 2x = n + xcan be introduced n = x, i.e., slowin fact, a number of steps walked ring. At this time, we let fastredirected the head of the list pHead, slowthe same position, then slowand fastwith every forward step, until fast == slow, when two pointers meet the node is the entrance to the ring.

 

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        # write code here
        if  pHead is None:
            return None
        if pHead.next is None:
            return None
        p = Pet
        q = pHead.next
        while p!=q:
            if q.next is not None and q.next.next is not None:
                p = p.next
                q = q.next.next
            else:
                break
        if p ==q:
            r = Pet
            p = p.next
            while r != p:
                r = r.next
                p = p.next
            return r 
        else:
            return None
        
                
            

 

 

Guess you like

Origin www.cnblogs.com/ansang/p/12033405.html