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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        auto it1=pHead1, it2 = pHead2;
        //没有人到达终点
        while(it1 != nullptr && it2 != nullptr){
            //如果等长,会出现相等的情况
            if(it1 == it2){
                return it1;
            }
            it1 = it1->next;
            it2 = it2->next;
        }
        //由于不等长,一定有一个先到达终点
        ListNode* longone;
        ListNode* shortone;
        ListNode* itcontinue;
        if(it1 == nullptr){
            shortone = pHead1;
            longone = pHead2;
            itcontinue = it2;
            
        }else{
            shortone = pHead2;
            longone = pHead1;
            itcontinue = it1;

        }
        auto itlong = longone;
        while(itcontinue){
            itcontinue = itcontinue->next;
            itlong = itlong->next;
        }
        auto itshort = shortone;
        while(itshort != itlong){
            itshort = itshort->next;
            itlong = itlong->next;
        }
        return itshort;
    }
};
posted @ 2021-03-28 10:11  rxh1999  阅读(35)  评论(0编辑  收藏  举报