HZFE / algorithms-solving

1 stars 0 forks source link

2022-08-15 #17

Open github-actions[bot] opened 2 years ago

gongpeione commented 2 years ago

141 Linked List Cycle

/*
 * @lc app=leetcode id=141 lang=typescript
 *
 * [141] Linked List Cycle
 */

// @lc code=start
/**
 * 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 {
    // const m = new Map();
    // while(head) {
    //     if (m.has(head)) {
    //         return true;
    //     }
    //     m.set(head, true);
    //     head = head.next;
    // }
    // return false;

    let slow = head;
    let fast = head;

    while (fast) {
        if (!fast.next?.next) {
            return false;
        }

        slow = slow.next;
        fast = fast.next.next;

        if (fast === slow) {
            return true;
        }
    }

    return false;
};
// @lc code=end

Nickname: Geeku From vscode-hzfe-algorithms