Home >Web Front-end >JS Tutorial >Algorithm to find the first common node of two linked lists in js
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.
Input two linked lists and find their first common node.
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.
/*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!