题解 | 链表中环的入口结点
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if (pHead == null) {
return null;
}
HashMap<ListNode, Boolean> exist = new HashMap<>();
ListNode current = pHead;
while(current != null) {
if (exist.get(current) != null) {
return current;
}
exist.put(current, true);
current = current.next;
}
return null;
}
}
判断链表里的环还是比较简单的,借助map来判断之前的节点是否存在过,然后遍历一遍整个链表就完成了


