First, the topic
1, examining
2. Analysis
Give two one-way linked list, if the two linked list with overlapping parts, output the first node of overlapping nodes, otherwise output null;
Second, the answer
1, Ideas:
Method One,
Aligns the two linked lists at the tail end, and begins traversing the linked list to find out if there are overlapping nodes.
①, calculate the length of two linked lists;
②, the long list is moved backwards, so that the tail of the two linked lists are aligned;
③, start the lookup node.
PublicListNode Getintersectionnode (ListNode heada, ListNode headb) {intLenA = 0, LenB = 0; ListNode node=Heada; //step1: Calculating the length of A and B nodes while(Node! =NULL) {node=Node.next; LenA++; } node=headb; while(Node! =NULL) {node=Node.next; LenB++; } //step2: Causes A, B to be aligned at the tail, and to begin to traverse backwards if(LenA >LenB) {Node=Heada; intGap = LenA-LenB; while(gap--> 0) Heada=Heada.next; } Else if(LenA <LenB) {Node=headb; intGap = LenB-LenA; while(gap--> 0) headb=Headb.next; } //step3: Finding the target node while(Heada! =NULL&& headb! =NULL) { if(Heada = =headb)returnHeada; Heada=Heada.next; HEADB=Headb.next; } returnHeada; }
Method Two,
There is no need to calculate the chain table length.
①, use pointer A to point to Heada, pointer to headb;
②, Adopt A while loop, when a! = B, both A and B move backwards, and when a = null, a points to headb, and when b = null, B points to Heada.
Eventually, a will traverse the Heada + headb,b to traverse the HEADB + Heada, eventually a, b encounters, the encounter point is null (no overlapping nodes), or node (the first overlapping node).
PublicListNode GetIntersectionNode2 (ListNode heada, ListNode headb) {if(Heada = =NULL|| HEADB = =NULL) return NULL; ListNode a= Heada, B =headb; while(A! =b) {a= (A = =NULL?headb:a.next); b= (b = =NULL?heada:b.next); } returnA; }
Intersection of Linked Lists