用js刷剑指offer(两个链表的第一个公共结点)

题目描述

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

牛客网链接

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
    }
}

posted @ 2019-11-06 21:39  1Shuan  阅读(274)  评论(0编辑  收藏  举报