13 Linked List Cycle 循环链表判断

63 阅读1分钟

leetcode.cn/problems/li…

利用键值的唯一性去判断是否有 cycle ,即将已经存在的 node 当成键值保存

解题思路

1.将已经遍历过的节点存入 Map 2.如果节点的next已经出现在Map中,返回 true 3.如果没有找到 cycle ,则返回 false

代码

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

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
    let map = new Map()
    while(head != null) {
        if(map.has(head)) {
            return true
        } else {
            map.set(head, true)
            head = head.next
        }
    }
    return false
};