Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find union of two given linked lists in Python
Suppose we have two sorted linked lists L1 and L2, we have to return a new sorted linked list that is the union of the two given lists. The union contains all unique elements from both lists in sorted order.
So, if the input is like L1 = [10,20,30,40,50,60,70] L2 = [10,30,50,80,90], then the output will be [10, 20, 30, 40, 50, 60, 70, 80, 90]
Algorithm
To solve this, we will follow these steps −
- Define a function solve(). This will take L1, L2
- if L1 is empty, then
- return L2
- if L2 is empty, then
- return L1
- if value of L1 < value of L2, then
- res := L1
- next of res := solve(next of L1, L2)
- otherwise when value of L2 < value of L1, then
- res := L2
- next of res := solve(next of L2, L1)
- otherwise (values are equal),
- res := L1
- next of res := solve(next of L1, next of L2)
- return res
Implementation
Let us see the following implementation to get better understanding −
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def solve(self, L1, L2):
if not L1:
return L2
if not L2:
return L1
if L1.val < L2.val:
res = L1
res.next = self.solve(L1.next, L2)
elif L2.val < L1.val:
res = L2
res.next = self.solve(L2.next, L1)
else:
res = L1
res.next = self.solve(L1.next, L2.next)
return res
ob = Solution()
L1 = make_list([10,20,30,40,50,60,70])
L2 = make_list([10,30,50,80,90])
print_list(ob.solve(L1, L2))
Output
[10, 20, 30, 40, 50, 60, 70, 80, 90, ]
How It Works
The recursive approach compares the values of the current nodes in both linked lists:
- Smaller value: Include it in the result and recursively process the remaining nodes
- Equal values: Include one copy and skip both nodes to avoid duplicates
- Base cases: When one list is empty, return the other list
Time and Space Complexity
- Time Complexity: O(m + n) where m and n are the lengths of the two linked lists
- Space Complexity: O(m + n) due to the recursive call stack
Conclusion
This recursive approach efficiently merges two sorted linked lists into their union by comparing node values and eliminating duplicates. The algorithm maintains the sorted order while ensuring each unique element appears only once in the result.
