Suppose we have two sorted linked lists L1 and L2, we have to make a new sorted linked list which contains the intersection of these two lists.
So, if the input is like L1 = [2, 4, 8] L2 = [3, 4, 8, 10], then the output will be [4, 8, ]
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) 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): head = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: l1 = l1.next elif l2.val < l1.val: l2 = l2.next else: cur.next = ListNode(l1.val) l1 = l1.next l2 = l2.next cur = cur.next return head.next ob = Solution() L1 = make_list([2, 4, 8]) L2 = make_list([3, 4, 8, 10]) print_list(ob.solve(L1, L2))
[2, 4, 8], [3, 4, 8, 10]
[4, 8, ]