[23] offer wins the inlet ring linked list node

Title Description

To a linked list, wherein if the ring comprises, find the entry ring node list, otherwise, outputs null.

Thinking

Two solutions ideas (understanding the second approach recommended drawing, will be more intuitive)

  • HashMap placed through each element, the end of the duplicate values ​​yet, no description ring. Encounters duplicate values, indicating that the entry ring node

  • Speed ​​pointer 1. If the full tail pointer go no faster encounter no ring pointer. If the speed of the pointer can be met, there must be described ring and the meeting point in the ring. How to determine the ring node

    • Also two pointers p1, p2 point to the head node, if there are n rings (n = b + c) nodes, a pointer p2 go ahead n steps, after the two pointers while walking. Nodes that meet the inlet ring.
      • Why is met when the inlet ring? p2 go ahead n steps, then walk at the same time. So go first to walk the equivalent distance of b + c. When the distance a away p1, p2 walked distance b + c + a. Just to the inlet ring.
    • How do you know the number of nodes in the ring n? Speed ​​may be determined by whether there is a pointer ring, and must meet point in the ring. From this node, while moving the count, when once again return to this node when you can get the number of nodes in the ring.
  • 2 the speed of the pointer. A first pointer speed to achieve little trouble, can come from the mathematical problem solving. When the speed of the pointer p1, p2 meet, will reposition the head node p2 and then move simultaneously. It is the meeting point of the inlet ring. Certify as follows:
    Here Insert Picture Description

import java.util.HashSet;

public class Offer23_EntryNodeOfLoop {

    public ListNode entryNodeOfLoop_HashSet(ListNode pHead) {
        if (pHead == null || pHead.next == null) return null;

        HashSet<ListNode> hashSet = new HashSet<ListNode>();
        while (pHead != null) {
            if (hashSet.contains(pHead)) {
                return pHead;
            }
            hashSet.add(pHead);
            pHead = pHead.next;
        }
        return null;
    }

    public ListNode entryNodeOfLoop_FastSlow(ListNode pHead) {
        if (pHead == null || pHead.next == null || pHead.next.next == null) return null;

        ListNode slow = pHead.next;
        ListNode fast = pHead.next.next;

        while (slow != fast) {
            if (fast.next == null || fast.next.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
        }

        fast = pHead;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

}

If you are interested can look at [more about a range of issues two lists intersect ]

Published 89 original articles · won praise 13 · views 20000 +

Guess you like

Origin blog.csdn.net/Dawn510/article/details/105247531