题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here while pHead: if pHead.val >= 20000: pHead.val -= 20000 return pHead pHead.val += 20000 pHead = pHead.next return None
一种取巧的方法,题目限定了节点值1 <=val <= 10000,只要每遍历过一个节点node后,给node的值增加k, k>10000,这样如果有环,找到入口的时候,那么有val+k>=k, val < k,只需要判定当前值是否大于等于k就可以得知了。