The proof of the solution to determine whether a linked list has rings, and to find the entry node of a ring, is given in a previous article.

OJ has a related topic

  • Leetcode 141. Circular linked lists
  • Leetcode 142. Circular linked list II
  • Niuke list central entry node

Now give my implementation code

func EntryNodeOfLoop(pHead *ListNode) *ListNode{
    var (
        slow = pHead
        fast = pHead
    )
    forfast ! =nil {
        slow = slow.Next
        fast = fast.Next
        if fast == nil {
            break
        }
        fast = fast.Next
        if slow == fast { // The nodes may have met
            break}}if fast == nil { // There is no loop
        return nil
    }
    fast = pHead
    // Find the entrance of the ring
    forslow ! = fast { slow = slow.Next fast = fast.Next }return fast
}
Copy the code