劍指offer(36)兩個鏈表中的第一個公共節點


題目描述

輸入兩個鏈表,找出它們的第一個公共結點。

 

題目分析

我發現關於鏈表的題都涉及雙指針,大家做的時候記得用雙指針。

題目理解了就很好做了,比較簡單,先在長的鏈表上跑,直到長的和短的一樣長,再一起跑,判斷節點相等的時候就可以了。

 

代碼

function FindFirstCommonNode(pHead1, pHead2) {
  const len1 = getLinkLength(pHead1),
    len2 = getLinkLength(pHead2);
  let pLong = pHead1,
    pShort = pHead2,
    lenGap = len1 - len2;
  if (len1 < len2) {
    pLong = pHead2;
    pShort = pHead1;
    lenGap = len2 - len1;
  }
  while (lenGap--) {
    pLong = pLong.next;
  }
  while (pLong !== null) {
    // pLong,pShort一起跑
    if (pLong.val === pShort.val) {
      return pLong;
    }
    pLong = pLong.next;
    pShort = pShort.next;
  }
  return null;
}
function getLinkLength(pHead) {
  let length = 0;
  while (pHead !== null) {
    pHead = pHead.next;
    length++;
  }
  return length;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM