# Intersection of Two Linked Lists in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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
• while headB is not null
• if headB in d
• Return null

## Example

Let us see the following implementation to get better understanding −

Live Demo

class ListNode:
def __init__(self, data, next = None):
self.data = data
self.next = next
class Solution(object):
"""
:rtype: ListNode
"""
dict = {}
if headB in dict:
return None
Intersect = ListNode(8, ListNode(4, ListNode(5)))
headA.next = ListNode(1, Intersect)
headB.next = ListNode(0, ListNode(1, Intersect))
ob1 = Solution()
print("Intersection:",op.data)

## Input

headA = ListNode(4)
headB.next = ListNode(0, ListNode(1, Intersect))
Intersected at '8'