题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
# 双指针法进行解题
1.使用快慢指针判断链表是否有环出现(有交点,则表示有环,没有交点则表示无环)
2.将交点固定,其中的一个指针置于头部。俩个指针一步一步走,直到有交点,该点即为共同的进入节点
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here # 判断链表是否有环,使用快慢指针的方式进行判断 slow = self.ishuan(pHead) if slow==None: return None fast = pHead while fast != slow: # 第二次相关的循环判断节点 # 链表不为空 slow = slow.next if fast.next: fast = fast.next else: return None return slow def ishuan(self, pHead): fast = pHead slow = pHead if not pHead: return pHead while slow and fast: # 链表不为空 slow = slow.next if fast.next: fast = fast.next.next else: return None if slow==fast: return slow # 快慢指针第一次相遇,判断是否有环出现,这时需要固定slow进行遍历 return None