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

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

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;
    }
};
全部评论

相关推荐

12-19 22:04
武汉大学 Java
点赞 评论 收藏
分享
11-14 16:15
已编辑
湖南工业大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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