剑指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
};

两个指针遍历的步骤: alt

全部评论
题目要求是O(n),这是表面的O(n),实际上是O(mn)
点赞 回复 分享
发布于 2023-08-11 15:45 上海

相关推荐

不愿透露姓名的神秘牛友
06-27 14:11
很喜欢小米的新车,校招薪资每月22k,攒多久能买?
测试糕手手:别看工资,先看现金流存款。有50W存款以上再考虑,车是消耗品,选适合自己的重要。你有钱就当我没说过
点赞 评论 收藏
分享
吴offer选手:HR:我KPI到手了就行,合不合适关我什么事
点赞 评论 收藏
分享
评论
10
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务