Home >Web Front-end >JS Tutorial >Algorithm to find the first common node of two linked lists in js

Algorithm to find the first common node of two linked lists in js

不言
不言Original
2018-07-23 11:00:141525browse

The content of this article is about the algorithm for finding the first common node of two linked lists in js. It has certain reference value. Friends in need can refer to it.

Problem description

Input two linked lists and find their first common node.

Analysis

Considering that the two linked lists are not the same length, calculate the length difference between the two linked lists, and then the long linked list must first complete the length difference, and then the two linked lists can be combined Walk.

Code implementation

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function FindFirstCommonNode(h1, h2)
{
    var h1Len = 0, h2Len = 0;
    var cur = h1;
    
    while(cur!==null){
        h1Len++;
        cur = cur.next;
    }
    
    cur = h2;
    while(cur!==null){
        h2Len++;
        cur = cur.next;
    }
    
    var distance = 0;
    var t1, t2;
    if(h1Len > h2Len){
        t1 = h1;
        t2 = h2;
        distance = h1Len - h2Len;
    }else{
        t1 = h2;
        t2 = h1;
        distance = h2Len - h1Len;
    }
    
    while(distance !== 0){
        t1 = t1.next;
        distance--;
    }
    
    while(t1 !== t2){
        t1 = t1.next;
        t2 = t2.next;
    }
    
    return t1;
}

Related recommendations:

Algorithm to realize the maximum value of sliding window in js

js Algorithm using two stacks to implement queue

The above is the detailed content of Algorithm to find the first common node of two linked lists in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn