Skip to content

Latest commit

 

History

History
45 lines (38 loc) · 802 Bytes

6.linked-list-cycle.md

File metadata and controls

45 lines (38 loc) · 802 Bytes

Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

JavaScript
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function (head) {

    if (head === null || head.next === null) {
        return false;
    }
    var tail1 = head.next;
    var tail2 = head.next.next;
    while (tail1 && tail2) {
        if (tail1 === tail2) {
            return true;
        }
        tail1 = tail1.next;
        if (tail2.next) {
            tail2 = tail2.next.next;
        }
        else {
            return false;
        }
    }

    return false;
};