LeetCode力扣 160. 相交鏈表 Intersection of Two Linked Lists 題解代碼 JavaScript

問題 https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

練習使用JavaScript解答

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

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
function getLength(list) {
    var i = 0;
    while(list) {
        ++i;
        list = list.next;
    }
    return i;
}
var getIntersectionNode = function(headA, headB) {
    var ia = getLength(headA),
        ib = getLength(headB);
    var cha = Math.abs(ia-ib);
    if(ia > ib)
        while(cha--)
            headA = headA.next;
    else
        while(cha--)
            headB = headB.next;
    while(headA && headB) {
        if(headA === headB)
            return headA;
        headA = headA.next;
        headB = headB.next;
    }
    return null;
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章