📌

100日アルゴリズム[13日目・片方向リスト]

2024/04/09に公開

問題

https://leetcode.com/problems/linked-list-cycle/

回答

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function hasCycle(head: ListNode | null): boolean {
    if(head == null || head.next == null) {
        return false
    }

    let front = head
    let back = head

    while(front.next !== null && back.next !== null && back.next.next !== null ) {
        back = back.next.next
        front = front.next

        if (front == back) {
            return true;
        }
    }
    return false;
};

片方向リストの最後のnodeのnext値が配列内のメモリを示すpointerになっており、pointerがループしているかをチェックしています。

Discussion