首页 > 代码库 > 剑指offer系列源码

剑指offer系列源码

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

两个链表相交成Y型。

#include <iostream>
#include <stdio.h>
using namespace std;
struct ListNode{
    int value;
    ListNode* next;
};
unsigned int getListLength(ListNode* pHead){
    unsigned int length = 0;
    ListNode* pNode = pHead;
    while(pNode){
        length++;
        pNode = pNode->next;
    }
    return length;
}
ListNode* findFirstCommonNode(ListNode* pHead1,ListNode* pHead2){
    unsigned int length1 = getListLength(pHead1);
    unsigned int length2 = getListLength(pHead2);
    int lengthDif = length1-length2;
    ListNode* pListHeadLong = pHead1;
    ListNode* pListHeadShort = pHead2;
    if(length1<length2){
        pListHeadLong = pHead2;
        pListHeadShort = pHead1;
        lengthDif =length2-length1;
    }
    for(int i=0;i<lengthDif;i++){
        pListHeadLong = pListHeadLong->next;
    }
    while(pListHeadLong&&pListHeadShort&&pListHeadLong!=pListHeadShort){
        pListHeadLong = pListHeadLong->next;
        pListHeadShort = pListHeadShort->next;
    }
    ListNode* pFirstCommonNOde = pListHeadLong;
    return pFirstCommonNOde;
}
int main() {
	return 0;
}


剑指offer系列源码