题解 | #两个链表的第一个公共结点#

两个链表的第一个公共结点

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

先测长度再双指针
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if(!pHead1||!pHead2)return nullptr;
        int n=0,m=0;
        ListNode *ta=pHead1,*tb=pHead2;
        while(ta=ta->next)
            ++n;
        while(tb=tb->next)
            ++m;
        ta=pHead1,tb=pHead2;
        if(n>m){
            for(int i=0;i<n-m;++i){
                ta=ta->next;
            }
        }
        else{
            for(int i=0;i<m-n;++i){
                tb=tb->next;
            }
        }
        while(ta!=tb){
            ta=ta->next;
            tb=tb->next;
        }
        return ta;
    }


全部评论

相关推荐

废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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