美文网首页
141. Linked List Cycle

141. Linked List Cycle

作者: Icytail | 来源:发表于2017-11-20 23:01 被阅读0次

Description:

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

Follow up:
Can you solve it without using extra space?

My code:

/**
 * 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) {
        return false;
    }
    if(!head.next) {
        return false;
    }
    let slow = head, fast = head.next;
    while(fast) {
        if(fast == slow) {
            return true;
        } else {
            fast = fast.next;
            if(!fast) {
                return false;
            } else {
                fast = fast.next;
                slow = slow.next;
            }
        }
    }
    return false;
};

Note: 两个指针,一个步长大,一个步长小,如果在某个时刻相等则表明有环。步长大的是分步进行的,在第一次next时还要判断是否为null,如果是就返回false,否则再两个指针next,不然可能会出现null不存在next的情况。

相关文章

网友评论

      本文标题:141. Linked List Cycle

      本文链接:https://www.haomeiwen.com/subject/ocgbvxtx.html