image.png

面试题 02.08. 环路检测

141. 环形链表

实现1:

  1. var hasCycle = function(head) {
  2. if (head == null || head.next == null) return false;
  3. let fast = head.next;
  4. let slow = head;
  5. while (fast != null) {
  6. if (fast == slow) return true;
  7. if (fast.next == null || fast.next.next == null) return false;
  8. slow = slow.next;
  9. fast = fast.next.next;
  10. }
  11. return false;
  12. };

实现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;
};

142. 环形链表 II