Daily Archives: June 17, 2016

Intersection of Two Linked Lists

leetcode 160.

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

Solution. I got the cool but trick solution from here. O(n) time, O(1) space.

Define a and b Node to travel through 2 lists. The point is to let both a and b travel complete 2 lists.

a travels: a1 -> a2 -> c1 -> c2 -> c3 -> b1 -> b2 -> b3 -> c1

b travels: b1 -> b2 -> b3 -> c1 -> c2 -> c3 -> a1 -> a2 -> c1

If order to let a, b travel, below code is presented:

def getIntersectionNode(self, headA, headB):
    a, b = headA, headB
    while a != b:
        a = a.next if a != None else headB
        b = b.next if b != None else headA
    return a

Check my code on github: link