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

# -*- 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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容