剑指52:两个链表的第一个公共结点

题目描述

输入两个链表,找出它们的第一个公共结点。
思路:2个单链表 先知道两者长度差值 然后长的先遍历到差值的起始位置 再同时后移。时间O(m+n)
/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if(pHead1==nullptr||pHead2==nullptr)
            return nullptr;
        int lengthlong = CountLen(pHead1);
        int lengthshort = CountLen(pHead2);
        int gap = lengthlong - lengthshort; 
        ListNode* pLong = pHead1;
        ListNode* pShort = pHead2;
        if(gap<0){
            pLong = pHead2;
            pShort = pHead1;
            gap = -gap;
        }
        for(int i=0;i<gap;i++)
            pLong = pLong->next;
        while(pLong && pShort &&pLong!=pShort){
            pLong = pLong->next;
            pShort = pShort->next;
        }
        return pLong;
    }
    int CountLen(ListNode* pHead)
    {
        int count = 0;
        while(pHead)
        {
            count++;
            pHead = pHead->next; 
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/yanbao4070/article/details/80231040