首页 > 其他 > 详细

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

时间:2021-03-28 12:40:22      阅读:24      评论:0      收藏:0      [点我收藏+]
/*
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;
    }
};

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

原文:https://www.cnblogs.com/N3ptuner/p/14587895.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!