美文网首页
链表中环的入口结点

链表中环的入口结点

作者: momo1023 | 来源:发表于2019-03-27 15:28 被阅读0次

    快慢指针f , s,两指针相遇时,f = 2* s, 设环长度为n,n = s
    再一个慢指针从链表头开始,两个慢指针相遇的地方则为入口

    # -*- 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 not pHead.next:
                return None
            fast = pHead
            slow = pHead
            while fast.next and fast.next.next:
                fast = fast.next.next
                slow = slow.next
                if fast == slow:
                    break
            slow2 = pHead
            while slow != slow2:
                slow = slow.next
                slow2 = slow2.next
            return slow
    

    相关文章

      网友评论

          本文标题:链表中环的入口结点

          本文链接:https://www.haomeiwen.com/subject/sfzbrttx.html