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.
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, ]
To solve this, we will follow these steps −
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))
[10,20,30,40,50,60,70], [10,30,50,80,90]
[10, 20, 30, 40, 50, 60, 70, 80, 90, ]