Intersection of Two Linked Lists in Python


Suppose we have two linked lists A and B, there are few elements in these linked lists. We have to return the reference of the intersection points. The inputs are intersectionVal = 8, A = [4,1,8,4,5], B = [5,0,1,8,4,5], skipA = 2 and skipB = 3, these are used to skip 2 elements from A and skip 3 elements from B.

To solve this, we will follow these steps −

  • Define a map called d
  • while headA is not null
    • d[headA] := 1
    • headA := next of headA
  • while headB is not null
    • if headB in d
      • return headB
    • headB := next of headB
  • Return null

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def getIntersectionNode(self, headA, headB):
      """
      :type head1, head1: ListNode
      :rtype: ListNode
      """
      dict = {}
      while headA:
         dict[headA]=1
         headA = headA.next
      while headB:
         if headB in dict:
            return headB
         headB = headB.next
      return None

Input

8
[4,1,8,4,5]
[5,0,1,8,4,5]
2
3

Output

Intersected at '8'
raja
Published on 16-Jan-2020 09:31:47
Advertisements