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

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

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

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        //遍历链表长度
        int len1=0;
        int len2=0;
        ListNode* l1=pHead1;
        ListNode* l2=pHead2;
        while(l1!=nullptr){
            len1++;
            l1=l1->next;
        }
        while(l2!=nullptr){
            len2++;
            l2=l2->next;
        }
        int d=abs(len1-len2);
        if(len1>len2){
            while(d!=0){
                pHead1=pHead1->next;
                d--;
            }
        }
        else{
            while(d!=0){
                pHead2=pHead2->next;
                d--;
            }
        }
        while(pHead1!=pHead2){
            pHead1=pHead1->next;
            pHead2=pHead2->next;
        }
        return pHead1;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
03-20 12:02
已编辑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务