- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- if headB in d
- Return null

## Example

Let us see the following implementation to get better understanding −

class ListNode: def __init__(self, data, next = None): self.data = data self.next = next 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 headA = ListNode(4) headB = ListNode(5) Intersect = ListNode(8, ListNode(4, ListNode(5))) headA.next = ListNode(1, Intersect) headB.next = ListNode(0, ListNode(1, Intersect)) ob1 = Solution() op = ob1.getIntersectionNode(headA, headB) print("Intersection:",op.data)

## Input

headA = ListNode(4) headB = ListNode(5) Intersect = ListNode(8, ListNode(4, ListNode(5))) headA.next = ListNode(1, Intersect) headB.next = ListNode(0, ListNode(1, Intersect))

## Output

Intersected at '8'

- Related Questions & Answers
- Intersection of Two Linked Lists in C++
- Find the Intersection Point of Two Linked Lists in Java
- Python program to find Intersection of two lists?
- Python - Intersection of multiple lists
- C# program to find Intersection of two lists
- Program to find linked list intersection from two linked list in Python
- Program to find union of two given linked lists in Python
- Python - Intersection of two String
- Intersection of Two Arrays II in Python
- Add two numbers represented by linked lists?
- Merge two sorted linked lists using C++.
- Program to interleave list elements from two linked lists in Python
- Program to add two polynomials given as linked lists using Python
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes in Python
- Multiply two numbers represented by Linked Lists in C++

Advertisements