剑指offer-面试题52-两个链表的第一个公共节点-链表

/*
题目:
	求两个链表的第一个公共节点。
*/
/*
思路:
	见代码。
*/
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>


using namespace std;

struct ListNode{
    int val;
    struct ListNode* next;
    ListNode(int x):
        val(x),next(nullptr){
    }
};

ListNode* FindFirstCommonNode(ListNode* pHead1,ListNode* pHead2){
    if(pHead1 == nullptr || pHead2 == nullptr){
        return nullptr;
    }
    int len1 = 0,len2 = 0;
    ListNode* p1 = pHead1, *p2 = pHead2;
    
    //得到链表1的长度
    while(p1 != nullptr){
        len1++;
        p1 = p1->next;
    }
    //得到链表2的长度
    while(p2 != nullptr){
        len2++;
        p2 = p2->next;
    }

    ListNode* pLong = pHead1;
    ListNode* pShort = pHead2;
    int step = len1 - len2;
    if(len1 < len2){
        pLong = pHead2;
        pShort = pHead1;
        step = len2 - len1;
    }

    //长链表先走几步,使得两个链表的长度相等
    while(step--){
        pLong = pLong->next;
    }
    
    //得到第一个重合的链表节点
    while(pLong != pShort){
        pLong = pLong->next;
        pShort = pShort->next;
    }

    return pLong;

}

int main(){
   ListNode* p1 = new ListNode(1);
   ListNode* p2 = new ListNode(2);
   ListNode* p3 = new ListNode(3);
   p1->next = p2;
   p2->next = p3;
   ListNode* res = FindFirstCommonNode(p1,p2);
   cout<<res->val<<endl;
}

   

原文地址:https://www.cnblogs.com/buaaZhhx/p/12075084.html