142. 环形链表 II
142. 环形链表 II - 力扣(LeetCode)
import java.util.HashSet;
import java.util.Set;public class LeetCode142 {public ListNode detectCycle(ListNode head) {Set<ListNode> listNodes = new HashSet<ListNode>();while (head != null){listNodes.add(head);//将链表节点存入集合head = head.next;//移动到下一位if (listNodes.contains(head)){return head;} //判断当前节点在集合中是否已经存在,若存在表明链表存在环,且该节点为入环的第一个节点}return null;}
}/*** Definition for singly-linked list.* class ListNode {* int val;* ListNode next;* ListNode(int x) {* val = x;* next = null;* }* }*/