题目描述
输入两个链表,找出它们的第一个公共结点。
分析
考虑到两个链表不一样长的情况,算出两个链表的长度差,然后长的链表要先把长度差走完,然后两个链表再一起走。
代码实现
/*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;
}