1 题目
链表无环返回null
链表有环返回环的入口节点
https://leetcode-cn.com/problems/linked-list-cycle-ii/
2 Java
2.1 方法一(HashSet查重)
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
HashSet<ListNode> set = new HashSet<>();
// 遍历链表
while(head != null){
// 操作
if(set.contains(head)) return head;
set.add(head);
// 下一节点
head = head.next;
}
return null;
}
}