用哈希表处理即可
141. 环形链表(简单)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
const map = new Map();
map.set(head, true);
while (head) {
const next = head.next;
if (map.get(next)) {
return true;
} else {
map.set(next, true);
head = next;
}
}
return false;
};
142. 环形链表 II(中等)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function (head) {
const map = new Map();
map.set(head, true);
while (head) {
const next = head.next;
if (map.get(next)) {
return next;
}
map.set(next, true);
head = next;
}
return null;
};