Prove safety Offer: entry ring node in the linked list (java version)

Title Description

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

Use HashSet storage node

If it does exist, this node is the ring node

public class Solution {
    public ListNode EntryNodeOfLoop(ListNode pHead){
        HashSet<ListNode> set = new HashSet<>();
        while(pHead.next!=null){
            if(set.contains(pHead)){
                return pHead;
            }
            set.add(pHead);
            pHead=pHead.next;
        }
        return null;
    }
}

Set the pointer speed

Setting a pointer to slow down one step each time, a fast 2-step each pass the pointer, if the ring, will meet in the ring.
Then let a pointer back to the beginning, a starting point to go, so a pointer resumes back away from the meeting point,
as two pointer speed, so that when the ring came from the entry point of origin when the pointer from the start point to go meet must also happens that the pointer reaches the loop entry point.
So who will meet 2, and just meet at the entry point of the ring.

public class Solution {
    public ListNode EntryNodeOfLoop(ListNode pHead){
        if(pHead == null || pHead.next==null || pHead.next.next==null) return null;
        ListNode node1 = pHead.next;
        ListNode node2 = pHead.next.next;
        while(node1 != node2) {
            if(node1.next!=null && node2.next.next!=null){
                node1 = node1.next;
                node2 = node2.next.next;
            }else{
                return null;
            }
        }
        node1 = pHead;
        while(node1!=node2){
            node1=node1.next;
            node2=node2.next;
        }
        return node1;
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/90246839