Difference of two Linked Lists using Merge sort

Given two Linked List, the task is to create a Linked List to store the difference of Linked List 1 with Linked List 2, i.e. the elements present in List 1 but not in List 2.


List1: 10 -> 15 -> 4 ->20,
List2: 8 -> 4 -> 2 -> 10
Output: 15 -> 20
In the given linked list elements 15 and 20 are present in the list 1 but not in list 2.

List1: 2 -> 4 -> 8 -> 10,
List2: 8 -> 10
Output: 2 -> 4
In the given linked list 1 elements 2 and 4 are present in the list 1 but not in list 2.


  • Sort both Linked Lists using merge sort.
  • Linearly scan both sorted lists to get the difference with two pointers on it p1 and p2 and compare the data of the nodes in the linked list and perform following in below three cases –
    1. If p1.data == p2.data then, p1.data cannot be in the difference list, So move the pointers p1 and p2 ahead.
    2. If p1.data > p2.data then, p1.data may be present in list 2 in further nodes, So move the pointer p2 ahead.
    3. If p1.data > p2.data then, p1.data cannot be present in list 2 now, So add the data of p1 into difference list and move pointer p1 ahead.
  • If the end of list 2 is reached, insert all the remaining elements of list 1 into the difference list.

Below is the implementation of the above approach.






# Python implementation to create
# a difference Linked List of 
# two Linked Lists
# Node of the Linked List
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
# Linked List
class linked_list:
    def __init__(self):
        self.head = None
    # Function to insert a node
    # at the end of Linked List
    def append(self, data):
        temp = Node(data)
        if self.head == None:
            self.head = temp
            p = self.head
            while p.next != None:
                p = p.next
            p.next = temp
    # Function to find the middle
    # node of the Linked List 
    def get_mid(self, head):
        if head == None:
            return head
        slow = fast = head
        while fast.next != None \
           and fast.next.next != None:
            slow = slow.next
            fast = fast.next.next
        return slow
    # Recursive method to merge the
    # two half after sorting 
    def merge(self, l, r):
        if l == None:return r
        if r == None:return l
        if l.data<= r.data:
            result = l
            result.next = \
                self.merge(l.next, r)
            result = r
            result.next = \
                self.merge(l, r.next)
        return result
    # Recusive method to divide the 
    # list into two half until 1 node left
    def merge_sort(self, head):
        if head == None or head.next == None:
            return head
        mid = self.get_mid(head)
        next_to_mid = mid.next
        mid.next = None
        left = self.merge_sort(head)
        right = self.merge_sort(next_to_mid)
        sorted_merge = self.merge(left, right)
        return sorted_merge
    # Function to print the list elements
    def display(self):
        p = self.head
        while p != None:
            print(p.data, end =' ')
            p = p.next
# Function to get the difference list
def get_difference(p1, p2):
    difference_list = linked_list()
    # Scan the lists 
    while p1 != None and p2 != None:
        # Condition to check if the 
        # Data of the both pointer are 
        # same then move ahead
        if p2.data == p1.data:
            p1 = p1.next
            p2 = p2.next
        # Condition to check if the 
        # Data of the first pointer is 
        # greater than second then 
        # move second pointer ahead
        elif p2.data<p1.data:
            p2 = p2.next
        # Condition when first pointer
        # data is greater than the 
        # second pointer then append
        # into the difference list and move
            p1 = p1.next
    # If end of list2 is reached, 
    # there may be some nodes in 
    # List 1 left to be scanned, 
    # they all will be inserted 
    # in the difference list
    if p2 == None:
        while p1:
            p1 = p1.next
    return difference_list
# Driver Code
if __name__ == '__main__':
    # Linked List 1
    list1 = linked_list()
    # Linked List 2
    list2 = linked_list()
    # Sort both the linkedlists
    list1.head = list1.merge_sort(
    list2.head = list2.merge_sort(
    # Get difference list
    result = get_difference(
               list1.head, list2.head
    if result.head:
    # if difference list is empty,
    # then lists are equal
        print('Lists are equal')



2 6 8

Time complexity: O(M Log M + N Log N).

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.