1. 程式人生 > 其它 >【LeetCode刷題篇】141.環形連結串列(JS)

【LeetCode刷題篇】141.環形連結串列(JS)

技術標籤:「 前端 」專欄# 【前端基礎(HTML JS CSS)】

給定一個連結串列,判斷連結串列中是否有環。

如果連結串列中有某個節點,可以通過連續跟蹤 next 指標再次到達,則連結串列中存在環。 為了表示給定連結串列中的環,我們使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該連結串列中沒有環。注意:pos 不作為引數進行傳遞,僅僅是為了標識連結串列的實際情況。

如果連結串列中存在環,則返回 true 。 否則,返回 false 。

 

進階:

你能用 O(1)(即,常量)記憶體解決此問題嗎?

 

示例 1
: 輸入:head = [3,2,0,-4], pos = 1 輸出:true 解釋:連結串列中有一個環,其尾部連線到第二個節點。 示例 2: 輸入:head = [1,2], pos = 0 輸出:true 解釋:連結串列中有一個環,其尾部連線到第一個節點。 示例 3: 輸入:head = [1], pos = -1 輸出:false 解釋:連結串列中沒有環。 提示: 連結串列中節點的數目範圍是 [0, 104] -105 <= Node.val <= 105 pos 為 -1 或者連結串列中的一個 有效索引 。

在這裡插入圖片描述

使用map,一路next通過has…看有無重複

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/** * @param {ListNode} head * @return {boolean} */ var hasCycle = function (head) { let dataMap = new Map() while (head) { if (dataMap.has(head)) { return true } dataMap.set(head, 1) head = head.next } return false };

快慢指標

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

JSON.stringify()

JSON.stringify有環就要報錯

var hasCycle = function(head) {
    try {
        JSON.stringify(head)
        return false
    } catch {
        return true
    }
};