23:链表中的环的入口结点(剑指offer第2版Python)

1、题目描述

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

2、代码详解

寻找链表中环的入口结点主要分成三个步骤:

首先是设置两个快慢指针,如果快慢指针相遇,则快慢指针必然都在环中;

然后从相遇的地方设置一个指针向后遍历并记录走的步数,当这个指针重新指到开始的位置的时候,当前对应的步数就是环中结点的数量k;

然后设置两个指针从链表开始,第一个节点先走k步,然后第二个指针指到链表的开始,两个指针每次都向后走一步,两个指针相遇的位置就是链表的入口。

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        if pHead == None:
            return None
        slow = pHead
        fast = pHead
        while fast != None and fast.next != None:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                break
        if fast == None or fast.next == None:
            return None

        fast = pHead
        while fast != slow:
            fast = fast.next
            slow = slow.next
        return fast




    # def EntryNodeOfLoop(self, pHead):
    #     slow = pHead
    #     fast = pHead
    #     while(fast != None and fast.next != None):
    #         slow = slow.next
    #         fast = fast.next.next
    #         if slow == fast:  # 第一次相撞
    #             fast = pHead  # 让快指针重头开始,相当于记录了环的节点数
    #             # 此时slow领先fast的步数即环的节点数
    #             while fast != slow:
    #                 fast = fast.next
    #                 slow = slow.next
    #             return slow
    #     return None
发布了184 篇原创文章 · 获赞 225 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/IOT_victor/article/details/104582146