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

不言
Release: 2018-07-23 11:00:14
Original
1527 people have browsed it

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template