142.环形链表2
思路(HashSet):
可以将节点每个都放入hashset中,然后遇到相同节点就break,没有相同的就遍历下一个节点依次放入hashset。
当break的时候,此时节点就是入口节点,返回它即可
代码实现:
/**
* 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) {
if (head == null) return null;
HashSet<ListNode> set = new HashSet<>();
int index = 0;
while (head != null) {
if (set.contains(head)) {
break;
}
set.add(head);
head = head.next;
}
return head;
}
}