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

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

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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        int List1Length = GetListLength(pHead1);
        int List2Length = GetListLength(pHead2);
        ListNode* pLongHead = pHead1;
        ListNode* pShortHead = pHead2;
        int diff = List1Length - List2Length;
        if (List2Length > List1Length){
            diff = List2Length - List1Length;
            pLongHead = pHead2;
            pShortHead = pHead1;
        }
        for(int i = 0; i < diff; i++){
            pLongHead = pLongHead->next;
        }
        ListNode* r = nullptr;
        while(pLongHead != nullptr && pShortHead != nullptr){
            if(pLongHead == pShortHead){
                r = pLongHead;
                break;
            }
            pLongHead = pLongHead->next;
            pShortHead = pShortHead->next;
        }
        return r;
    }
    int GetListLength(ListNode* pHead){
        int r = 0;
        while(pHead != nullptr){
            pHead = pHead->next;
            r++;
        }
        return r;
    }
};
全部评论

相关推荐

牛客20485985...:抱抱😘,首先你还有春招,然后就算这时候没上岸也没关系,大部分人都是这样,毕业了再找也成,最后工作只是生活的一小部分,找到工作也不是一个必须的事情。不要气馁不要焦虑你只是陷入了短暂的低谷,你也一直有退路
点赞 评论 收藏
分享
04-13 10:07
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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