Write a program to find the node at which the intersection of the singly linked lists begins.
For example, the following, linked lists:
A:--a1→a2
———————-
———————— C1→C2→C3
———————–
B:b1→b2→b3
Begin to intersect at node C1.
Notes:
? If The linked lists has no intersection at all, return null.
? The linked lists must retain their original structure after the function returns.
? You may assume there is no cycles anywhere in the entire linked structure.
? Your code should preferably run in O (n) time and use only O (1) memory.
A very elegant solution:
ListNode*Getintersectionnode (ListNode*Heada, ListNode*HEADB) {ListNode*P1=Heada; ListNode*P2=HEADB;if(P1== NULL ||P2== NULL)return NULL; while(P1!= NULL &&P2!= NULL &&P1!=P2) {P1=P1 -Next P2=P2 -Next// //any time they collide or reach end together without colliding //Then return to any one of the pointers. // if(P1==P2)returnP1;// //If One of them reaches the end earlier then reuse it //By moving it to the beginning of other list. //Once both of them go through reassigning, //They 'll is equidistant from the collision point. // if(P1== NULL) P1=HEADB;if(P2== NULL) P2=Heada; }returnP1;//above does not seem to need, the above path should have a return value, should not all AC}
Python solution:
# Definition for singly-linked list.# class ListNode:# def __init__ (self, x):# self.val = x# self.next = None class solution: # @param the Listnodes # @return The intersected ListNode def getintersectionnode(self, Heada, headb):Cura,curb = heada,headb Lena,lenb =0,0 whileCurA is not None: LenA + =1CurA = Cura.next whileCurB is not None: LenB + =1CurB = Curb.next Cura,curb = heada,headbifLenA > LenB: forIinchRange (LENA-LENB): CurA = Cura.nextelifLenB > LenA: forIinchRange (Lenb-lena): CurB = Curb.next whileCurB! = Cura:curb = Curb.next CurA = Cura.nextreturnCura/*the Solution isstraightforward:maintaining pointersinchThe lists under the constraint that both lists has the same number of nodes starting fromThe pointers. We need to calculate the length of each list though. So O (N) forTime andO (1) forspace.*/
Leetcode 160Intersection of Linked Lists