剑指offer JZ36 题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function FindFirstCommonNode(pHead1, pHead2)
{
// write code here
if(!pHead1 || !pHead2) return null
let p1 = pHead1,
p2 = pHead2
while (p1 != p2) {
p1 = (p1 === null ? pHead2 : p1.next)
p2 = (p2 === null ? pHead1 : p2.next)
}
return p1 // 或者返回p2都行
}
module.exports = {
FindFirstCommonNode : FindFirstCommonNode
};
两个指针遍历的步骤: