题解 | #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        # first check if it has a loop or not
        # if it has a loop, return the first position fast meet the slow
        # else return None
        def hascycle(head):
            if not head:
                return
            fast = slow = head
            while fast and fast.next:
                fast = fast.next.next
                slow = slow.next
                if fast == slow:
                    return fast
            return

        # slow1 at the head and the slow2 at the first meeting position
        # the next time they meet is the position where the ring started
        slow1 = hascycle(pHead)
        if not slow1:
            return
        else:
            slow2 = pHead
            while slow2 != slow1:
                slow1 = slow1.next
                slow2 = slow2.next
            return slow2

全部评论

相关推荐

ResourceUt...:楼主有自己的垃圾箱,公司也有自己的人才库
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务