(链表)力扣160题解: 找出两个链表的交点—TypeScri

2021-03-25  本文已影响0人  wxyzcctn
/**
 * 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 l1 = headA;
    let l2 = headB;
    while( l1 !== l2 ){
        l1 = l1 === null ? headB : l1.next;
        l2 = l2 === null ? headA : l2.next;
    }
    return l1;
};

说明

headA: 2-6-4
l1: 2-6-4 + 1-5
l2: 1-5 + 2-6-4
headB: 1-5

headA: 4-1-8-4-5
l1: 4-1-8-4-5 + 5-0-1-[8-4-5]
l2: 5-0-1-8-4-5 + 4-1-[8-4-5]
headB: 5-0-1-8-4-5

headA: 4-1-8-3-7
l1: 4-1-8-3-7 + 5-0-1-[8]-4-5
l2: 5-0-1-8-4-5 + 4-1-[8]-3-7
headB: 5-0-1-8-4-5

这种方法可以类推到找数组中的相同子数组

上一篇下一篇

猜你喜欢

热点阅读