题解 | #链表中环的入口结点#
链表中环的入口结点
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): # tmp = pHead while pHead.val > 0: pHead.val = -pHead.val pHead = pHead.next if not pHead: return None pHead.val = -pHead.val return pHead
不知道为什么要把这个问题复杂化
直接遍历,每个数变为原来的相反数(负值)
如果next遇到负值,说明是环入口,再把这个值变回正值
我称之为“插旗法”,变负值就是插旗。