面试题 02.08. 环路检测
141. 环形链表
实现1:
var hasCycle = function(head) {
if (head == null || head.next == null) return false;
let fast = head.next;
let slow = head;
while (fast != null) {
if (fast == slow) return true;
if (fast.next == null || fast.next.next == null) return false;
slow = slow.next;
fast = fast.next.next;
}
return false;
};
实现2:
var hasCycle = function(head) {
if (head == null || head.next == null) return false;
let fast = head.next;
let slow = head;
while (fast != slow) {
if (fast == null || fast.next == null) return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
};