题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
# -*- coding:utf-8 -*-
# from numpy import heaviside
# 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
slow = pHead
fast = pHead
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
if fast == slow: # 判断是否有环
fast = pHead # 快指针回到链表头
while fast != slow: # 分别一步一步遍历
fast = fast.next
slow = slow.next
return slow # 环入口
return None
主要思路
- 先判断链表是否有环,找到相遇的节点。
- 快指针回到链表头,慢指针继续在相遇节点,两个指针同步逐个元素遍历链表。
- 再次相遇的地方就是环的入口。