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 −
- head := a new node with value 0
- cur := head
- while l1 and l2 are not empty, do
- if value of l1 < value of l2, then
- l1 := next of l1
- otherwise when value of l2 < value of l1, then
- l2 := next of l2
- otherwise,
- next of cur := a new node with value same as value of l1
- l1 := next of l1
- l2 := next of l2
- cur := next of cur
- if value of l1 < value of l2, then
- return next of head
Let us see the following implementation to get better understanding −
Example
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): 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))
Input
[2, 4, 8], [3, 4, 8, 10]
Output
[4, 8, ]