# 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.
Examples:

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

Approach:

• 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.

## C++

 `//C++ program to implement above approach` `#include ` `class` `Node {``public``:``    ``int` `data;``    ``Node* next;` `    ``Node(``int` `val) : data(val), next(nullptr) {}``};` `class` `LinkedList {``public``:``    ``Node* head;` `    ``LinkedList() : head(nullptr) {}` `    ``// Function to insert a node at the end of the linked list``    ``void` `append(``int` `data) {``        ``Node* temp = ``new` `Node(data);``        ``if` `(head == nullptr) {``            ``head = temp;``        ``} ``else` `{``            ``Node* p = head;``            ``while` `(p->next != nullptr) {``                ``p = p->next;``            ``}``            ``p->next = temp;``        ``}``    ``}` `    ``// Function to find the middle node of the linked list``    ``Node* get_mid(Node* head) {``        ``if` `(head == nullptr) {``            ``return` `head;``        ``}``        ``Node* slow = head;``        ``Node* fast = head;``        ``while` `(fast->next != nullptr && fast->next->next != nullptr) {``            ``slow = slow->next;``            ``fast = fast->next->next;``        ``}``        ``return` `slow;``    ``}` `    ``// Recursive method to merge two halves after sorting``    ``Node* merge(Node* l, Node* r) {``        ``if` `(l == nullptr) ``return` `r;``        ``if` `(r == nullptr) ``return` `l;` `        ``Node* result;``        ``if` `(l->data <= r->data) {``            ``result = l;``            ``result->next = merge(l->next, r);``        ``} ``else` `{``            ``result = r;``            ``result->next = merge(l, r->next);``        ``}``        ``return` `result;``    ``}` `    ``// Recursive method to divide the list into two halves until 1 node left``    ``Node* merge_sort(Node* head) {``        ``if` `(head == nullptr || head->next == nullptr) {``            ``return` `head;``        ``}``        ``Node* mid = get_mid(head);``        ``Node* next_to_mid = mid->next;``        ``mid->next = nullptr;``        ``Node* left = merge_sort(head);``        ``Node* right = merge_sort(next_to_mid);``        ``Node* sorted_merge = merge(left, right);``        ``return` `sorted_merge;``    ``}` `    ``// Function to print the list elements``    ``void` `display() {``        ``Node* p = head;``        ``while` `(p != nullptr) {``            ``std::cout << p->data << ``" "``;``            ``p = p->next;``        ``}``        ``std::cout << std::endl;``    ``}``};` `// Function to get the difference list``LinkedList get_difference(Node* p1, Node* p2) {``    ``LinkedList difference_list;``    ``// Scan the lists``    ``while` `(p1 != nullptr && p2 != nullptr) {``        ``// Condition to check if the data of both pointers are the same, then move ahead``        ``if` `(p2->data == p1->data) {``            ``p1 = p1->next;``            ``p2 = p2->next;``        ``} ``else` `if` `(p2->data < p1->data) { ``// Condition to check if the data of the second pointer is smaller than the first, then move the second pointer ahead``            ``p2 = p2->next;``        ``} ``else` `{ ``// Condition when the data of the first pointer is greater than the second, then append into the difference list and move``            ``difference_list.append(p1->data);``            ``p1 = p1->next;``        ``}``    ``}` `    ``// If the 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``    ``while` `(p1 != nullptr) {``        ``difference_list.append(p1->data);``        ``p1 = p1->next;``    ``}` `    ``return` `difference_list;``}` `int` `main() {``    ``// Linked List 1``    ``LinkedList list1;``    ``list1.append(2);``    ``list1.append(6);``    ``list1.append(8);``    ``list1.append(1);` `    ``// Linked List 2``    ``LinkedList list2;``    ``list2.append(4);``    ``list2.append(1);``    ``list2.append(9);` `    ``// Sort both linked lists``    ``list1.head = list1.merge_sort(list1.head);``    ``list2.head = list2.merge_sort(list2.head);` `    ``// Get the difference list``    ``LinkedList result = get_difference(list1.head, list2.head);` `    ``if` `(result.head) {``        ``result.display();``    ``} ``else` `{``        ``std::cout << ``"Lists are equal"` `<< std::endl;``    ``}` `    ``return` `0;``}`

## Java

 `class` `Node {``    ``int` `data;``    ``Node next;` `    ``Node(``int` `data) {``        ``this``.data = data;``        ``this``.next = ``null``;``    ``}``}` `class` `LinkedList {``    ``Node head;` `    ``LinkedList() {``        ``head = ``null``;``    ``}` `    ``// Function to insert a node at the end of Linked List``    ``void` `append(``int` `data) {``        ``Node newNode = ``new` `Node(data);``        ``if` `(head == ``null``) {``            ``head = newNode;``        ``} ``else` `{``            ``Node current = head;``            ``while` `(current.next != ``null``) {``                ``current = current.next;``            ``}``            ``current.next = newNode;``        ``}``    ``}` `    ``// Function to find the middle node of the Linked List``    ``Node getMid(Node head) {``        ``if` `(head == ``null``) {``            ``return` `head;``        ``}``        ``Node slow = head;``        ``Node fast = head;``        ``while` `(fast.next != ``null` `&& fast.next.next != ``null``) {``            ``slow = slow.next;``            ``fast = fast.next.next;``        ``}``        ``return` `slow;``    ``}` `    ``// Recursive method to merge two halves after sorting``    ``Node merge(Node left, Node right) {``        ``if` `(left == ``null``) {``            ``return` `right;``        ``}``        ``if` `(right == ``null``) {``            ``return` `left;``        ``}` `        ``Node result;``        ``if` `(left.data <= right.data) {``            ``result = left;``            ``result.next = merge(left.next, right);``        ``} ``else` `{``            ``result = right;``            ``result.next = merge(left, right.next);``        ``}``        ``return` `result;``    ``}` `    ``// Recursive method to divide the list into two halves until 1 node left``    ``Node mergeSort(Node head) {``        ``if` `(head == ``null` `|| head.next == ``null``) {``            ``return` `head;``        ``}` `        ``Node mid = getMid(head);``        ``Node nextToMid = mid.next;``        ``mid.next = ``null``;``        ``Node left = mergeSort(head);``        ``Node right = mergeSort(nextToMid);``        ``return` `merge(left, right);``    ``}` `    ``// Function to print the list elements``    ``void` `display() {``        ``Node current = head;``        ``while` `(current != ``null``) {``            ``System.out.print(current.data + ``" "``);``            ``current = current.next;``        ``}``        ``System.out.println();``    ``}` `    ``// Function to get the difference list``    ``static` `LinkedList getDifference(Node p1, Node p2) {``        ``LinkedList differenceList = ``new` `LinkedList();` `        ``// Scan the lists``        ``while` `(p1 != ``null` `&& p2 != ``null``) {` `            ``// Condition to check if the data of both pointers are the same, then move ahead``            ``if` `(p2.data == p1.data) {``                ``p1 = p1.next;``                ``p2 = p2.next;``            ``} ``else` `if` `(p2.data < p1.data) { ``// Condition to check if the data of the second pointer is smaller than the first, then move the second pointer ahead``                ``p2 = p2.next;``            ``} ``else` `{ ``// Condition when the data of the first pointer is greater than the second, then append into the difference list and move``                ``differenceList.append(p1.data);``                ``p1 = p1.next;``            ``}``        ``}` `        ``// If the 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``        ``while` `(p1 != ``null``) {``            ``differenceList.append(p1.data);``            ``p1 = p1.next;``        ``}` `        ``return` `differenceList;``    ``}``}` `public` `class` `Main {``    ``public` `static` `void` `main(String[] args) {``        ``// Linked List 1``        ``LinkedList list1 = ``new` `LinkedList();``        ``list1.append(``2``);``        ``list1.append(``6``);``        ``list1.append(``8``);``        ``list1.append(``1``);` `        ``// Linked List 2``        ``LinkedList list2 = ``new` `LinkedList();``        ``list2.append(``4``);``        ``list2.append(``1``);``        ``list2.append(``9``);` `        ``// Sort both the linked lists``        ``list1.head = list1.mergeSort(list1.head);``        ``list2.head = list2.mergeSort(list2.head);` `        ``// Get the difference list``        ``LinkedList result = LinkedList.getDifference(list1.head, list2.head);` `        ``if` `(result.head != ``null``) {``            ``result.display();``        ``} ``else` `{``            ``System.out.println(``"Lists are equal"``);``        ``}``    ``}``}`

## Python3

 `# 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``        ``else``:``            ``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)``        ``else``:``            ``result ``=` `r``            ``result.``next` `=` `\``                ``self``.merge(l, r.``next``)``        ``return` `result` `    ``# Recursive 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``        ``print``()` `# 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

## C#

 `using` `System;``class` `Node {``    ``public` `int` `data;``    ``public` `Node next;` `    ``public` `Node(``int` `data)``    ``{``        ``this``.data = data;``        ``this``.next = ``null``;``    ``}``}` `class` `LinkedList {``    ``public` `Node head;` `    ``public` `LinkedList() { head = ``null``; }` `    ``// Function to insert a node at the end of Linked List``    ``public` `void` `Append(``int` `data)``    ``{``        ``Node newNode = ``new` `Node(data);``        ``if` `(head == ``null``) {``            ``head = newNode;``        ``}``        ``else` `{``            ``Node current = head;``            ``while` `(current.next != ``null``) {``                ``current = current.next;``            ``}``            ``current.next = newNode;``        ``}``    ``}` `    ``// Function to find the middle node of the Linked List``    ``public` `Node GetMid(Node head)``    ``{``        ``if` `(head == ``null``) {``            ``return` `head;``        ``}``        ``Node slow = head;``        ``Node fast = head;``        ``while` `(fast.next != ``null``               ``&& fast.next.next != ``null``) {``            ``slow = slow.next;``            ``fast = fast.next.next;``        ``}``        ``return` `slow;``    ``}` `    ``// Recursive method to merge two halves after sorting``    ``public` `Node Merge(Node left, Node right)``    ``{``        ``if` `(left == ``null``) {``            ``return` `right;``        ``}``        ``if` `(right == ``null``) {``            ``return` `left;``        ``}` `        ``Node result;``        ``if` `(left.data <= right.data) {``            ``result = left;``            ``result.next = Merge(left.next, right);``        ``}``        ``else` `{``            ``result = right;``            ``result.next = Merge(left, right.next);``        ``}``        ``return` `result;``    ``}` `    ``// Recursive method to divide the list into two halves``    ``// until 1 node left``    ``public` `Node MergeSort(Node head)``    ``{``        ``if` `(head == ``null` `|| head.next == ``null``) {``            ``return` `head;``        ``}` `        ``Node mid = GetMid(head);``        ``Node nextToMid = mid.next;``        ``mid.next = ``null``;``        ``Node left = MergeSort(head);``        ``Node right = MergeSort(nextToMid);``        ``return` `Merge(left, right);``    ``}` `    ``// Function to print the list elements``    ``public` `void` `Display()``    ``{``        ``Node current = head;``        ``while` `(current != ``null``) {``            ``Console.Write(current.data + ``" "``);``            ``current = current.next;``        ``}``        ``Console.WriteLine();``    ``}` `    ``// Function to get the difference list``    ``public` `static` `LinkedList GetDifference(Node p1, Node p2)``    ``{``        ``LinkedList differenceList = ``new` `LinkedList();` `        ``// Scan the lists``        ``while` `(p1 != ``null` `&& p2 != ``null``) {``            ``// Condition to check if the data of both``            ``// pointers are the same, then move ahead``            ``if` `(p2.data == p1.data) {``                ``p1 = p1.next;``                ``p2 = p2.next;``            ``}``            ``else` `if` `(p2.data``                     ``< p1.data) ``// Condition to check if the``                                ``// data of the second``                                ``// pointer is smaller than``                                ``// the first, then move the``                                ``// second pointer ahead``            ``{``                ``p2 = p2.next;``            ``}``            ``else` `{ ``// Condition when the data of the first``                   ``// pointer is greater than the second,``                   ``// then append into the difference list``                   ``// and move``                ``differenceList.Append(p1.data);``                ``p1 = p1.next;``            ``}``        ``}` `        ``// If the 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``        ``while` `(p1 != ``null``) {``            ``differenceList.Append(p1.data);``            ``p1 = p1.next;``        ``}` `        ``return` `differenceList;``    ``}``}` `class` `Program {``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``// Linked List 1``        ``LinkedList list1 = ``new` `LinkedList();``        ``list1.Append(2);``        ``list1.Append(6);``        ``list1.Append(8);``        ``list1.Append(1);` `        ``// Linked List 2``        ``LinkedList list2 = ``new` `LinkedList();``        ``list2.Append(4);``        ``list2.Append(1);``        ``list2.Append(9);` `        ``// Sort both the linked lists``        ``list1.head = list1.MergeSort(list1.head);``        ``list2.head = list2.MergeSort(list2.head);` `        ``// Get the difference list``        ``LinkedList result = LinkedList.GetDifference(``            ``list1.head, list2.head);` `        ``if` `(result.head != ``null``) {``            ``result.Display();``        ``}``        ``else` `{``            ``Console.WriteLine(``"Lists are equal"``);``        ``}``    ``}``}`

## Javascript

 `class Node {``  ``constructor(data) {``    ``this``.data = data;``    ``this``.next = ``null``;``  ``}``}` `class LinkedList {``  ``constructor() {``    ``this``.head = ``null``;``  ``}` `  ``// Function to insert a node at the end of Linked List``  ``append(data) {``    ``const newNode = ``new` `Node(data);``    ``if` `(``this``.head === ``null``) {``      ``this``.head = newNode;``    ``} ``else` `{``      ``let current = ``this``.head;``      ``while` `(current.next !== ``null``) {``        ``current = current.next;``      ``}``      ``current.next = newNode;``    ``}``  ``}` `  ``// Function to find the middle node of the Linked List``  ``getMid(head) {``    ``if` `(head === ``null``) {``      ``return` `head;``    ``}``    ``let slow = head;``    ``let fast = head;``    ``while` `(fast.next !== ``null` `&& fast.next.next !== ``null``) {``      ``slow = slow.next;``      ``fast = fast.next.next;``    ``}``    ``return` `slow;``  ``}` `  ``// Recursive method to merge two halves after sorting``  ``merge(left, right) {``    ``if` `(left === ``null``) {``      ``return` `right;``    ``}``    ``if` `(right === ``null``) {``      ``return` `left;``    ``}` `    ``let result;``    ``if` `(left.data <= right.data) {``      ``result = left;``      ``result.next = ``this``.merge(left.next, right);``    ``} ``else` `{``      ``result = right;``      ``result.next = ``this``.merge(left, right.next);``    ``}``    ``return` `result;``  ``}` `  ``// Recursive method to divide the list into two halves until 1 node left``  ``mergeSort(head) {``    ``if` `(head === ``null` `|| head.next === ``null``) {``      ``return` `head;``    ``}` `    ``const mid = ``this``.getMid(head);``    ``const nextToMid = mid.next;``    ``mid.next = ``null``;``    ``const left = ``this``.mergeSort(head);``    ``const right = ``this``.mergeSort(nextToMid);``    ``return` `this``.merge(left, right);``  ``}` `  ``// Function to print the list elements``  ``display() {``    ``let current = ``this``.head;``    ``let result = ``''``;``    ``while` `(current !== ``null``) {``      ``result += current.data + ``' '``;``      ``current = current.next;``    ``}``    ``console.log(result.trim());``  ``}` `  ``// Function to get the difference list``  ``static getDifference(p1, p2) {``    ``const differenceList = ``new` `LinkedList();` `    ``// Scan the lists``    ``while` `(p1 !== ``null` `&& p2 !== ``null``) {``      ``// Condition to check if the data of both pointers are the same, then move ahead``      ``if` `(p2.data === p1.data) {``        ``p1 = p1.next;``        ``p2 = p2.next;``      ``} ``else` `if` `(p2.data < p1.data) {``        ``// Condition to check if the data of the second pointer is smaller than the first, then move the second pointer ahead``        ``p2 = p2.next;``      ``} ``else` `{``        ``// Condition when the data of the first pointer is greater than the second, then append into the difference list and move``        ``differenceList.append(p1.data);``        ``p1 = p1.next;``      ``}``    ``}` `    ``// If the 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``    ``while` `(p1 !== ``null``) {``      ``differenceList.append(p1.data);``      ``p1 = p1.next;``    ``}` `    ``return` `differenceList;``  ``}``}` `// Linked List 1``const list1 = ``new` `LinkedList();``list1.append(2);``list1.append(6);``list1.append(8);``list1.append(1);` `// Linked List 2``const list2 = ``new` `LinkedList();``list2.append(4);``list2.append(1);``list2.append(9);` `// Sort both the linked lists``list1.head = list1.mergeSort(list1.head);``list2.head = list2.mergeSort(list2.head);` `// Get the difference list``const result = LinkedList.getDifference(list1.head, list2.head);` `if` `(result.head !== ``null``) {``  ``result.display();``} ``else` `{``  ``console.log(``"Lists are equal"``);``}`

Output
```2 6 8

```

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