HZFE / algorithms-solving

1 stars 0 forks source link

2022-08-07 #9

Open github-actions[bot] opened 2 years ago

github-actions[bot] commented 2 years ago

160. Intersection of Two Linked Lists

gongpeione commented 2 years ago

160 Intersection of Two Linked Lists

/*
 * @lc app=leetcode id=160 lang=typescript
 *
 * [160] Intersection of Two Linked Lists
 */

// @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 getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
    let pA = headA;
    let pB = headB;

    // if we move the pointer to the other list's head when it reaches the end of the list
    // we can make sure that the second round of loop would be synchronized in both list
    while(pA !== pB) {
        // if pA equals to null, then move pA to headB
        if (!pA) {
            pA = headB;
        } else {
        // else move the pointer to the next node
            pA = pA.next;
        }

        if (!pB) {
            pB = headA;
        } else {
            pB = pB.next;
        }
    }

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

Nickname: Geeku From vscode-hzfe-algorithms