【链表】链表中环的入口结点

2019-08-14  本文已影响0人  一个想当大佬的菜鸡
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        # write code here
        hasLoop = self.hasLoop(pHead)
        if hasLoop == None:
            return None
        n = self.nodeNum(hasLoop)
        fast = slow = pHead
        for i in range(n):
            fast = fast.next
        while fast != slow:
            fast = fast.next
            slow = slow.next
        return slow
    def hasLoop(self, pHead):
        if pHead == None or pHead.next == None:
            return None
        slow, fast = pHead, pHead.next
        while fast != None:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return slow
        return None
    def nodeNum(self, pHead):
        p = pHead.next
        n = 1
        while p != pHead:
            p = p.next
            n += 1
        return n
上一篇 下一篇

猜你喜欢

热点阅读