題目描述
輸入兩個鏈表,找出它們的第一個公共結點,
牛客網鏈接
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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/131558.html
標籤:其他
