题目描述

输入两个链表,找出它们的第一个公共结点。

牛客网链接

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

js代码

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function FindFirstCommonNode(pHead1, pHead2)
{
    // write code here
    let len1 = FindLength(pHead1) 
    let len2 = FindLength(pHead2) 
    if (len1 > len2) {
        pHead1 = FindFirstCommonNodeHelp(pHead1, len1-len2)
    }else {
        pHead2 = FindFirstCommonNodeHelp(pHead2, len2-len1)
    }
    while (pHead1) {
        if (pHead1 === pHead2) return pHead1
        pHead1 = pHead1.next
        pHead2 = pHead2.next
    }
    
    function FindLength(p) {
      if (p === null) return 0
      let sum = 0
      while (p) {
        sum++
        p = p.next
      }
      return sum
    }
    function FindFirstCommonNodeHelp(pHead, step) {
        while (step--) {
            pHead = pHead.next
        }
        return pHead
    }
}

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄