环形链表 II

tech2026-01-26  15

 

 

[a+ m(b+c) +b] x2 = a+ n(b+c) +b=> a+ b  = (n- 2m)(b+c)=> a = (n- 2m)(b+c) -b  && c =(b+c) -b=> a = c + (n-2m-1)(b+c) // 即 a 与 c 相差环长的整数倍=> 则一个节点A从头出发 一个节点B从相遇点出发;A B 相遇的地方就是成环点

另:一般当n=2 m=0 时 a==c

func detectCycle(head *ListNode) *ListNode { one := head if one == nil { return nil } two := head for ; one.Next != nil; { one = one.Next // fmt.Println(one.Val) if two.Next != nil && two.Next.Next != nil { two = two.Next.Next } else { return nil } if one == two { break } } if one.Next == nil { return nil } for anotherOne := head; anotherOne != one; anotherOne = anotherOne.Next { one = one.Next } return one }

 

最新回复(0)