Skip to content

Files

Latest commit

 

History

History
64 lines (56 loc) · 1.45 KB

0160. Intersection of Two Linked Lists.md

File metadata and controls

64 lines (56 loc) · 1.45 KB

Linked List

Screen Shot 2023-03-06 at 6 02 22 PM

Screen Shot 2023-03-06 at 6 02 32 PM

Screen Shot 2023-03-06 at 6 02 47 PM

Brute Force

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

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function(headA, headB) {
    let pA = headA;
    while(pA) {
        let pB = headB;
        while(pB) {
            if(pA === pB) {
                return pA;
            }
            pB = pB.next;
        }
        pA = pA.next;
    }
    return null;
};

Two Pointer

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

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function(headA, headB) {
    let pA = headA, pB = headB;
    while(pA !== pB) {
        pA = pA ? pA.next : headB;
        pB = pB ? pB.next : headA;
    }
    return pA;
};