def shared_by_switching(a, b):
pa, pb = a, b
while pa is not pb:
pa = pa.next if pa is not None else b
pb = pb.next if pb is not None else a
return pa
print(shared_by_switching(a, b).val, shared_by_switching(b, a).val)
7 7
Here are both walks on the example, with 9a for the 9 in a and 9b for the one in b:
On step 8 both stand on a 9, but on different nodes, so the loop goes on. On step 9 both are on the 7.
Say a has x nodes of its own, b has y, and they share z. When x=y, both reach the shared node on step x, and the loop ends there.
Otherwise pa reaches it on its second pass, after x+z+1+y steps: its own part, the shared part, one step on None, then b's own part. pb gets there after y+z+1+x steps, the same number. Here x=2, y=3 and z=3, so that's step 9.
If the lists share nothing, z=0, and both are None at the same moment, after x+y+1 steps, or after x when x=y. It returns None. Lists of 2 and 3 nodes took 6 steps, and two lists of 3 took 3.