题解 | #10.两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
set遍历即可
function FindFirstCommonNode(pHead1, pHead2)
{
let set = new Set();
while(pHead1 != null){
set.add(pHead1);
pHead1 = pHead1.next;
}
while(pHead2 != null){
if( set.has(pHead2) ) return pHead2;
pHead2 = pHead2.next;
}
return null;
}
另一种方法,看题解就可以明白
function FindFirstCommonNode(pHead1, pHead2)
{
let l1 = pHead1,
l2 = pHead2;
while(l1!=l2){
l1 = l1!=null ? l1.next : pHead2;
l2 = l2!=null ? l2.next : pHead1;
}
return l1;
}