Problem Definition:
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.
Solution 1:seems a little bit long, but it ' s straightforward.
1 defGetintersectionnode (Heada, headb):2L1,l2=0,03ha,hb=heada,headb4 whileha!=None:5Ha=Ha.next6L1+=17 whilehb!=None:8hb=Hb.next9L2+=1TenHa,hb=heada,headb#Throwback One ifL1>L2: ASub=l1-L2 - whileSub>0: -Ha=Ha.next theSub-=1 - Else: -sub=l2-L1 - whileSub>0: +hb=Hb.next -Sub-=1 + whileha!=HB: AHa=Ha.next athb=Hb.next - returnHa
A: a1→a2 C1 →c2→c3 B: b1→ b2→b3
Solution 2: Using the same principle, different interpretations.
1) Traverse two linked lists at the same time. The HA traverses the list of Heada, and the HB traverses the linked list of headb.
2) When Ha reaches the end of the chain, it points to headb, continues the traversal, and when HB reaches the end of the chain, it points to Heada and continues the traversal.
3) When HA==HB, returns ha.
Look at the chestnuts below:
a: b2 →b3
ha from A1 to C3, then points to B1. At this point HB is pointing to C3. The
next moment, Ha arrives at B2, while HB arrives at A1. This is achieved in the same way as in the previous solution () effect from the same two nodes to the stub point
to continue the traversal and reach C1.
In the above process, each step (HA and HB are moved) are judged HA==HB, once established immediately return.
As a result of the following differences
1) Two tables have a common sub-chain, but the two tables are unequal, then the second round will find the intersection node
2) Two tables have a common sub-chain, and two tables equal length, then in the first round of time can find the intersection node
3) Two tables have no common sub-chain, becomes empty at the same time in the first or second round traversal, returning an empty
code:
1 def Getintersectionnode (Heada, headb): 2 ha,hb=heada,headb3while ha!=HB:4 if else headb5 ifelse heada 6 return ha
leetcode#160 intersection of the Linked Lists