剑指offer-链表中环的入口结点-链表-python ***
题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路
第一步,用两个快慢指针找环中相汇点。分别用slow, fast指向链表头部,slow每次走一步,fast每次走二步,直到fast == slow找到在环中的相汇点。
第二步,找环的入口。当fast == slow时,假设slow走过x个节点,则fast走过2x个节点。设环中有n个节点,因为fast比slow多走一圈(n个节点),所以有等式2x = n + x,可以推出n = x,即slow实际上走了一个环的步数。这时,我们让fast重新指向链表头部pHead,slow的位置不变,然后slow和fast一起向前每次走一步,直到fast == slow,此时两个指针相遇的节点就是环的入口。
# -*- 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 pHead is None: return None if pHead.next is None: return None p = pHead q = pHead.next while p!=q: if q.next is not None and q.next.next is not None: p = p.next q = q.next.next else: break if p ==q: r = pHead p = p.next while r != p: r = r.next p = p.next return r else: return None

浙公网安备 33010602011771号