【剑指Offer】55.链表中环的入口结点(Python实现)

题目描述

给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

解法一:快慢指针法

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
# -*- 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 or not pHead.next or not pHead.next.next:
            return None
        slow = pHead.next
        fast = slow.next
        # 找到相遇点
        while fast != slow and fast.next:
            slow = slow.next
            fast = fast.next.next
        if slow == fast:
            # 慢指针回到表头,快指针留在相遇点,二者同步往前直到相遇在入口结点
            slow = pHead
            while slow != fast:
                fast = fast.next
                slow = slow.next
            return slow
        return None
发布了101 篇原创文章 · 获赞 73 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36936730/article/details/104752049