Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program to Find Intersection and Union of Two Linked Lists

Python Program to Find Intersection and Union of Two Linked Lists

In this Python program, we will be implementing the intersection and union operations on two linked lists. Linked lists are data structures that consist of a sequence of elements, where each element points to the next element in the sequence.

Problem Statement

Given two linked lists, we need to find the intersection and union of these lists.

Python Program to Find Intersection and Union of Two Linked Lists

```class Node:
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):

def insert(self, data):
new_node = Node(data)
else:
while current.next:
current = current.next
current.next = new_node

def display(self):
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

def find_intersection(self, other_list):
while current:
if other_list.search(current.data):
intersection.insert(current.data)
current = current.next
return intersection

def search(self, data):
while current:
if current.data == data:
return True
current = current.next
return False

def find_union(self, other_list):

while current:
union.insert(current.data)
current = current.next

while other_current:
if not union.search(other_current.data):
union.insert(other_current.data)
other_current = other_current.next

return union

list1.insert(1)
list1.insert(2)
list1.insert(3)

list2.insert(3)
list2.insert(4)
list2.insert(5)

list1.display()

list2.display()

intersection_result = list1.find_intersection(list2)
print("Intersection:")
intersection_result.display()

union_result = list1.find_union(list2)
print("Union:")
union_result.display()```

How It Works

1. In this program, we define a `Node` class to represent elements in the linked list and a `LinkedList` class to manage the linked list operations.
2. The `find_intersection` method iterates through the first list and checks if each element is present in the second list.
3. If yes, it adds the element to the `intersection` linked list.
4. The `find_union` method combines the elements of both lists while avoiding duplicates.
5. The `search` method is used to search for an element in the linked list.

Input / Output

You May Also Like

Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...