var hasCycle = function (head) {
let dataMap = new Set();
while (head) {
if (dataMap.has(head)) {
return true;
}
dataMap.add(head);
head = head.next;
}
return false;
};
快指针每次移动两步,慢指针每次移动一步
如果存在环,快指针与慢指针就会相遇,否则快指针会到达链表结尾
public class Solution {
public boolean hasCycle(ListNode head) {
if (head== null || head.next ==null)return false;
ListNode fast = head.next.next, slow = head.next;
while (fast != slow) {
if (fast == null || fast.next ==null) return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}