For example, the following, linked lists:
A: a1→a2 c1→c2→c3 B: b1→b2→b3
Begin to intersect at node C1.
The idea is clear, first determine the length of the two and calculate the difference between the absolute value of the dis, let the longer linked list first take the dis step, and then two pointers go together. If two pointers are equal, they are returned, otherwise there is no intersection when the pointer reaches null.
The AC code is as follows:
voidGetLength (ListNode *head,int&Len) {Len=0; ListNode* h=Head; while(h) {h=h->Next; Len++; }} ListNode*getinsersection (listnode* heada,listnode* headb,intLenaintLenB) { if(!lena | |!LenB)returnNULL; //Heada and headb is not NULL if(lena<LenB)returngetinsersection (Headb,heada,lenb,lena); //Lena>=lenb intdis = lena-LenB; ListNode* Fir=heada,*sec =headb; while(dis) {fir=fir->Next; --dis; } while(fir&&sec) { if(fir==sec)returnfir; Else{fir= fir->Next; SEC= sec->Next; } } returnNULL; } ListNode*getintersectionnode (ListNode *heada, ListNode *headb) { intLena=0, lenb=0; GetLength (Heada,lena); GetLength (HEADB,LENB); returngetinsersection (HEADA,HEADB,LENA,LENB); }
Leetcode "160" intersection of Linked Lists