The entry node of the ring in the JZ55 linked list

Title description

For a linked list, if it contains a ring, please find the entry node of the ring of the linked list, otherwise, output null.

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
import java.util.HashMap;
import java.util.Map;

public class Solution {
    
    

    public ListNode EntryNodeOfLoop(ListNode pHead)
    {
    
    
        Map<ListNode,Integer> map = new HashMap();
        ListNode p = pHead;
        while (p != null){
    
    
            map.put(p,map.getOrDefault(p,0)+1);
            if (map.getOrDefault(p,0) == 2) {
    
    
                return p;
            }
            p = p.next;
        }
        return null;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41620020/article/details/108591867