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.
1 classsolution (object):2 defGetintersectionnode (self, Heada, headb):3 """4 : Type Head1, Head1:listnode5 : Rtype:listnode6 """7 8n =self.getlength (Heada)9m =self.getlength (HEADB)Ten One ifN <m: A returnSelf.getintersectionnode (headb, Heada) - - forIinchRange (nm): theHeada =Heada.next - - whileHeada andheadb: - ifID (heada) = =ID (headb): + returnHeada -Heada =Heada.next +HEADB =Headb.next A returnNone at - defGetLength (Self, head): -n =0 - whileHead: -Head =Head.next -n + = 1 in returnN
1. Always first operate the list with the shorter length.
2. Use the id (heada) = = ID (headb) to determine if two node is the same
Leetcode 160. Intersection of linked lists