Intersection of two Linked List

Last Updated : 19 Apr, 2026

Given two singly distinct linked lists, create a new linked list that contains the intersection of elements present in both lists.

Note: The order of nodes in this list should be the same as they nodes appear in LinkedList1.

Examples:

Input: LinkedList1: 9->6->4->2->3->8 , LinkedList2: 1->2->8->6
Output: 6->2->8
Explanation: Nodes 6, 2 and 8 are common in both of the lists and the order will be according to LinkedList1.

Input: LinkedList1: 5->3->1->13->14 , LinkedList2: 3->13

Output: 3->13
Explanation: Nodes 3 and 13 are common in both of the lists and the order will be according to LinkedList1.

Input:
head1: 4 -> 2 -> 4 -> 1 -> 2 -> 8
head2: 2 -> 4 -> 6 -> 2 -> 4
Output:
Intersection: 4 -> 2
Explanation: Common elements in both lists are 4 and 2. Even though they appear multiple times, each element is included only once in the intersection list.

Try It Yourself
redirect icon

[Naive Approach] Using Two Nested Loops - O(n * m) Time and O(n) Space

Traverse the first linked list and for each element, check whether it exists in the second linked list. If yes and not already added, insert it into the result list.

C++
#include <iostream>
using namespace std;

// Node definition
class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = NULL;
    }
};

// Check if value exists in list
bool isPresent(Node* head, int val) {
    while (head) {
        if (head->data == val)
            return true;
        head = head->next;
    }
    return false;
}

// Naive appraoch for Intersection of two linkedlist
Node* findIntersection(Node* head1, Node* head2) {

    Node* result = NULL;
    Node* tail = NULL;

    while (head1 != NULL) {

        if (isPresent(head2, head1->data) &&
            !isPresent(result, head1->data)) {

            Node* newNode = new Node(head1->data);

            if (result == NULL)
                result = tail = newNode;
            else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        head1 = head1->next;
    }

    return result;
}

// Print function
void printList(Node* head) {
    while (head) {
        cout << head->data << " ";
        head = head->next;
    }
    cout << endl;
}

// Driver Code
int main() {

    // LinkedList1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
    Node* head1 = new Node(9);
    head1->next = new Node(6);
    head1->next->next = new Node(4);
    head1->next->next->next = new Node(2);
    head1->next->next->next->next = new Node(3);
    head1->next->next->next->next->next = new Node(8);

    // LinkedList2: 1 -> 2 -> 8 -> 6
    Node* head2 = new Node(1);
    head2->next = new Node(2);
    head2->next->next = new Node(8);
    head2->next->next->next = new Node(6);

    Node* intersection = findIntersection(head1, head2);

    cout << "Intersection: ";
    printList(intersection);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Node definition
struct Node {
    int data;
    struct Node* next;
};

struct Node* createNode(int x) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->next = NULL;
    return newNode;
}

// Check if value exists in list
int isPresent(struct Node* head, int val) {
    while (head) {
        if (head->data == val)
            return 1;
        head = head->next;
    }
    return 0;
}

// Naive approach for Intersection of two linked list
struct Node* findIntersection(struct Node* head1, struct Node* head2) {
    struct Node* result = NULL;
    struct Node* tail = NULL;
    while (head1!= NULL) {
        if (isPresent(head2, head1->data) &&!isPresent(result, head1->data)) {
            struct Node* newNode = createNode(head1->data);
            if (result == NULL)
                result = tail = newNode;
            else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        head1 = head1->next;
    }
    return result;
}

// Print function
void printList(struct Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

// Driver Code
int main() {
    // LinkedList1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
    struct Node* head1 = createNode(9);
    head1->next = createNode(6);
    head1->next->next = createNode(4);
    head1->next->next->next = createNode(2);
    head1->next->next->next->next = createNode(3);
    head1->next->next->next->next->next = createNode(8);
    
    // LinkedList2: 1 -> 2 -> 8 -> 6
    struct Node* head2 = createNode(1);
    head2->next = createNode(2);
    head2->next->next = createNode(8);
    head2->next->next->next = createNode(6);
    
    struct Node* intersection = findIntersection(head1, head2);
    printf("Intersection: ");
    printList(intersection);
    return 0;
}
Java
import java.util.*;

// Node definition
class Node {
    public int data;
    public Node next;
    
    Node(int x) {
        data = x;
        next = null;
    }
}

public class Main {
    // Check if value exists in list
    static boolean isPresent(Node head, int val) {
        while (head!= null) {
            if (head.data == val)
                return true;
            head = head.next;
        }
        return false;
    }

    // Naive approach for Intersection of two linked list
    static Node findIntersection(Node head1, Node head2) {
        Node result = null;
        Node tail = null;
        while (head1!= null) {
            if (isPresent(head2, head1.data) && !isPresent(result, head1.data)) {
                Node newNode = new Node(head1.data);
                if (result == null)
                    result = tail = newNode;
                else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            head1 = head1.next;
        }
        return result;
    }

    // Print function
    static void printList(Node head) {
        while (head!= null) {
            System.out.print(head.data + " ");
            head = head.next;
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {
        // LinkedList1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
        Node head1 = new Node(9);
        head1.next = new Node(6);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(2);
        head1.next.next.next.next = new Node(3);
        head1.next.next.next.next.next = new Node(8);
        
        // LinkedList2: 1 -> 2 -> 8 -> 6
        Node head2 = new Node(1);
        head2.next = new Node(2);
        head2.next.next = new Node(8);
        head2.next.next.next = new Node(6);
        
        Node intersection = findIntersection(head1, head2);
        System.out.print("Intersection: ");
        printList(intersection);
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Check if value exists in list
def isPresent(head, val):
    while head:
        if head.data == val:
            return True
        head = head.next
    return False

# Naive approach for Intersection of two linked list
def findIntersection(head1, head2):
    result = None
    tail = None
    while head1!= None:
        if isPresent(head2, head1.data) and not isPresent(result, head1.data):
            newNode = Node(head1.data)
            if result == None:
                result = tail = newNode
            else:
                tail.next = newNode
                tail = newNode
        head1 = head1.next
    return result

# Print function
def printList(head):
    while head:
        print(head.data, end=" ")
        head = head.next
    print()

# Driver Code
if __name__ == '__main__':
    # LinkedList1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
    head1 = Node(9)
    head1.next = Node(6)
    head1.next.next = Node(4)
    head1.next.next.next = Node(2)
    head1.next.next.next.next = Node(3)
    head1.next.next.next.next.next = Node(8)

    # LinkedList2: 1 -> 2 -> 8 -> 6
    head2 = Node(1)
    head2.next = Node(2)
    head2.next.next = Node(8)
    head2.next.next.next = Node(6)

    intersection = findIntersection(head1, head2)
    print("Intersection: ", end="")
    printList(intersection)
C#
using System;

public class Node
{
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

public class Program
{
    // Check if value exists in list
    public static bool isPresent(Node head, int val)
    {
        while (head != null)
        {
            if (head.data == val)
                return true;
            head = head.next;
        }
        return false;
    }

    // Naive approach for Intersection
    public static Node findIntersection(Node head1, Node head2)
    {
        Node result = null;
        Node tail = null;

        while (head1 != null)
        {
            if (isPresent(head2, head1.data) && !isPresent(result, head1.data))
            {
                Node newNode = new Node(head1.data);

                if (result == null)
                    result = tail = newNode;
                else
                {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            head1 = head1.next;
        }

        return result;
    }

    // Print function
    public static void printList(Node head)
    {
        while (head != null)
        {
            Console.Write(head.data + " ");
            head = head.next;
        }
        Console.WriteLine();
    }

    // Driver Code
    public static void Main()
    {
        // LinkedList1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
        Node head1 = new Node(9);
        head1.next = new Node(6);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(2);
        head1.next.next.next.next = new Node(3);
        head1.next.next.next.next.next = new Node(8);

        // LinkedList2: 1 -> 2 -> 8 -> 6
        Node head2 = new Node(1);
        head2.next = new Node(2);
        head2.next.next = new Node(8);
        head2.next.next.next = new Node(6);

        Node intersection = findIntersection(head1, head2);

        Console.Write("Intersection: ");
        printList(intersection);
    }
}
JavaScript
class Node {
    constructor(data, next = null) {
        this.data = data;
        this.next = next;
    }
}

// Check if value exists in list
function isPresent(head, val) {
    while (head) {
        if (head.data === val)
            return true;
        head = head.next;
    }
    return false;
}

// Naive approach for Intersection of two linkedlist
function findIntersection(head1, head2) {
    let result = null;
    let tail = null;

    while (head1!== null) {
        if (isPresent(head2, head1.data) && !isPresent(result, head1.data)) {
            const newNode = new Node(head1.data);

            if (result === null)
                result = tail = newNode;
            else {
                tail.next = newNode;
                tail = newNode;
            }
        }
        head1 = head1.next;
    }

    return result;
}

// Print function
function printList(head) {
    while (head) {
        process.stdout.write(`${head.data} `);
        head = head.next;
    }
    console.log();
}

// Driver Code
const head1 = new Node(9);
head1.next = new Node(6);
head1.next.next = new Node(4);
head1.next.next.next = new Node(2);
head1.next.next.next.next = new Node(3);
head1.next.next.next.next.next = new Node(8);

const head2 = new Node(1);
head2.next = new Node(2);
head2.next.next = new Node(8);
head2.next.next.next = new Node(6);

const intersection = findIntersection(head1, head2);

console.log('Intersection:'); 
printList(intersection);

Output
Intersection: 6 2 8 

[Better Approach] Using Sorting - O(n Log n + m Log m) Time and O(n + m) Space

Sort both linked lists and use two pointers to efficiently find common elements.

Steps

  1. Sort both lists
  2. Compare nodes one by one. If equal, add to the result. Else more pointer in the linked list having smaller value.
  3. Continue until one list ends.
  4. Return result
C++
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = NULL;
    }
};

// Split list
Node* split(Node* head) {
    Node* slow = head;
    Node* fast = head;

    while (fast->next && fast->next->next) {
        slow = slow->next;
        fast = fast->next->next;
    }

    Node* temp = slow->next;
    slow->next = NULL;
    return temp;
}

// Merge two sorted lists
Node* merge(Node* a, Node* b) {
    if (!a) return b;
    if (!b) return a;

    if (a->data < b->data) {
        a->next = merge(a->next, b);
        return a;
    } else {
        b->next = merge(a, b->next);
        return b;
    }
}

// Merge Sort
Node* mergeSort(Node* head) {
    if (!head || !head->next)
        return head;

    Node* second = split(head);

    head = mergeSort(head);
    second = mergeSort(second);

    return merge(head, second);
}

// Sorting appraoch for Intersection of two linkedlist
Node* findIntersection(Node* h1, Node* h2) {

    // Sort both lists
    h1 = mergeSort(h1);
    h2 = mergeSort(h2);

    Node dummy(-1);
    Node* tail = &dummy;

    // Two pointer traversal
    while (h1 && h2) {

        if (h1->data < h2->data) {
            h1 = h1->next;
        }
        else if (h1->data > h2->data) {
            h2 = h2->next;
        }
        else {
            // Common element
            tail->next = new Node(h1->data);
            tail = tail->next;

            h1 = h1->next;
            h2 = h2->next;
        }
    }

    return dummy.next;
}

// Print list
void printList(Node* head) {
    while (head) {
        cout << head->data << " ";
        head = head->next;
    }
    cout << endl;
}

int main() {

    // List1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
    Node* head1 = new Node(9);
    head1->next = new Node(6);
    head1->next->next = new Node(4);
    head1->next->next->next = new Node(2);
    head1->next->next->next->next = new Node(3);
    head1->next->next->next->next->next = new Node(8);

    // List2: 1 -> 2 -> 8 -> 6
    Node* head2 = new Node(1);
    head2->next = new Node(2);
    head2->next->next = new Node(8);
    head2->next->next->next = new Node(6);

    Node* result = findIntersection(head1, head2);

    cout << "Intersection: ";
    printList(result);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

struct Node* Node(int x) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->next = NULL;
    return newNode;
}

// Split list
struct Node* split(struct Node* head) {
    struct Node* slow = head;
    struct Node* fast = head;

    while (fast->next && fast->next->next) {
        slow = slow->next;
        fast = fast->next->next;
    }

    struct Node* temp = slow->next;
    slow->next = NULL;
    return temp;
}

// Merge two sorted lists
struct Node* merge(struct Node* a, struct Node* b) {
    if (!a) return b;
    if (!b) return a;

    if (a->data < b->data) {
        a->next = merge(a->next, b);
        return a;
    } else {
        b->next = merge(a, b->next);
        return b;
    }
}

// Merge Sort
struct Node* mergeSort(struct Node* head) {
    if (!head ||!head->next)
        return head;

    struct Node* second = split(head);

    head = mergeSort(head);
    second = mergeSort(second);

    return merge(head, second);
}

// Intersection using Sorting
struct Node* findIntersection(struct Node* h1, struct Node* h2) {

    // Sort both lists
    h1 = mergeSort(h1);
    h2 = mergeSort(h2);

    struct Node dummy = {-1};
    struct Node* tail = &dummy;

    // Two pointer traversal
    while (h1 && h2) {

        if (h1->data < h2->data) {
            h1 = h1->next;
        }
        else if (h1->data > h2->data) {
            h2 = h2->next;
        }
        else {
            // Common element
            tail->next = Node(h1->data);
            tail = tail->next;

            h1 = h1->next;
            h2 = h2->next;
        }
    }

    return dummy.next;
}

// Print list
void printList(struct Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {

    // List1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
    struct Node* head1 = Node(9);
    head1->next = Node(6);
    head1->next->next = Node(4);
    head1->next->next->next = Node(2);
    head1->next->next->next->next = Node(3);
    head1->next->next->next->next->next = Node(8);

    // List2: 1 -> 2 -> 8 -> 6
    struct Node* head2 = Node(1);
    head2->next = Node(2);
    head2->next->next = Node(8);
    head2->next->next->next = Node(6);

    struct Node* result = findIntersection(head1, head2);

    printf("Intersection: ");
    printList(result);

    return 0;
}
Java
class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

class Solution {

    // Split list
    public Node split(Node head) {
        Node slow = head;
        Node fast = head;

        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        Node temp = slow.next;
        slow.next = null;
        return temp;
    }

    // Merge two sorted lists
    public Node merge(Node a, Node b) {
        if (a == null) return b;
        if (b == null) return a;

        if (a.data < b.data) {
            a.next = merge(a.next, b);
            return a;
        } else {
            b.next = merge(a, b.next);
            return b;
        }
    }

    // Merge Sort
    public Node mergeSort(Node head) {
        if (head == null || head.next == null)
            return head;

        Node second = split(head);

        head = mergeSort(head);
        second = mergeSort(second);

        return merge(head, second);
    }

    // Intersection using Sorting
    public Node findIntersection(Node h1, Node h2) {

        // Sort both lists 
        h1 = mergeSort(h1);
        h2 = mergeSort(h2);

        Node dummy = new Node(-1);
        Node tail = dummy;

        while (h1 != null && h2 != null) {

            if (h1.data < h2.data) {
                h1 = h1.next;
            }
            else if (h1.data > h2.data) {
                h2 = h2.next;
            }
            else {
                tail.next = new Node(h1.data);
                tail = tail.next;

                h1 = h1.next;
                h2 = h2.next;
            }
        }

        return dummy.next;
    }

    // Print list
    public void printList(Node head) {
        while (head != null) {
            System.out.print(head.data + " ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {

        Solution obj = new Solution();

        Node head1 = new Node(9);
        head1.next = new Node(6);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(2);
        head1.next.next.next.next = new Node(3);
        head1.next.next.next.next.next = new Node(8);

        Node head2 = new Node(1);
        head2.next = new Node(2);
        head2.next.next = new Node(8);
        head2.next.next.next = new Node(6);

        Node result = obj.findIntersection(head1, head2);

        System.out.print("Intersection: ");
        obj.printList(result);
    }
}
Python
from typing import Optional


class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


# Split list
def split(head):
    slow = head
    fast = head

    while fast.next and fast.next.next:
        slow = slow.next
        fast = fast.next.next

    temp = slow.next
    slow.next = None
    return temp


# Merge two sorted lists
def merge(a, b):
    if not a: return b
    if not b: return a

    if a.data < b.data:
        a.next = merge(a.next, b)
        return a
    else:
        b.next = merge(a, b.next)
        return b


# Merge Sort
def mergeSort(head):
    if not head or not head.next:
        return head

    second = split(head)

    head = mergeSort(head)
    second = mergeSort(second)

    return merge(head, second)


# Intersection using Sorting
def findIntersection(h1, h2):

    # Sort both lists
    h1 = mergeSort(h1)
    h2 = mergeSort(h2)

    dummy = Node(-1)
    tail = dummy

    # Two pointer traversal
    while h1 and h2:

        if h1.data < h2.data:
            h1 = h1.next
        elif h1.data > h2.data:   
            h2 = h2.next
        else:
            # Common element
            tail.next = Node(h1.data)
            tail = tail.next

            h1 = h1.next
            h2 = h2.next

    return dummy.next   

# Print list
def printList(head):
    while head:
        print(head.data, end=" ")
        head = head.next
    print()


if __name__ == "__main__":

    # List1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
    head1 = Node(9)
    head1.next = Node(6)
    head1.next.next = Node(4)
    head1.next.next.next = Node(2)
    head1.next.next.next.next = Node(3)
    head1.next.next.next.next.next = Node(8)

    # List2: 1 -> 2 -> 8 -> 6
    head2 = Node(1)
    head2.next = Node(2)
    head2.next.next = Node(8)
    head2.next.next.next = Node(6)

    result = findIntersection(head1, head2)

    print("Intersection: ", end="")
    printList(result)
C#
using System;

public class Node
{
    public int data;
    public Node next;

    public Node(int x)
    {
        data = x;
        next = null;
    }
}

public class Program
{
    // Split list
    public static Node split(Node head)
    {
        Node slow = head;
        Node fast = head;

        while (fast.next != null && fast.next.next != null)
        {
            slow = slow.next;
            fast = fast.next.next;
        }

        Node temp = slow.next;
        slow.next = null;
        return temp;
    }

    // Merge two sorted lists
    public static Node merge(Node a, Node b)
    {
        if (a == null) return b;
        if (b == null) return a;

        if (a.data < b.data)
        {
            a.next = merge(a.next, b);
            return a;
        }
        else
        {
            b.next = merge(a, b.next);
            return b;
        }
    }

    // Merge Sort
    public static Node mergeSort(Node head)
    {
        if (head == null || head.next == null)
            return head;

        Node second = split(head);

        head = mergeSort(head);
        second = mergeSort(second);

        return merge(head, second);
    }

    // Intersection using Sorting
    public static Node findIntersection(Node h1, Node h2)
    {
        h1 = mergeSort(h1);
        h2 = mergeSort(h2);

        Node dummy = new Node(-1);
        Node tail = dummy;

        while (h1 != null && h2 != null)
        {
            if (h1.data < h2.data)
            {
                h1 = h1.next;
            }
            else if (h1.data > h2.data)
            {
                h2 = h2.next;
            }
            else
            {
                tail.next = new Node(h1.data);
                tail = tail.next;

                h1 = h1.next;
                h2 = h2.next;
            }
        }

        return dummy.next;
    }

    // Print list
    public static void printList(Node head)
    {
        while (head != null)
        {
            Console.Write(head.data + " ");
            head = head.next;
        }
        Console.WriteLine();
    }

    public static void Main()
    {
        Node head1 = new Node(9);
        head1.next = new Node(6);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(2);
        head1.next.next.next.next = new Node(3);
        head1.next.next.next.next.next = new Node(8);

        Node head2 = new Node(1);
        head2.next = new Node(2);
        head2.next.next = new Node(8);
        head2.next.next.next = new Node(6);

        Node result = findIntersection(head1, head2);

        Console.Write("Intersection: ");
        printList(result);
    }
}
JavaScript
class Node {
    constructor(data, next=null) {
        this.data = data;
        this.next = next;
    }
}

// Split list
function split(head) {
    let slow = head;
    let fast = head;

    while (fast.next && fast.next.next) {
        slow = slow.next;
        fast = fast.next.next;
    }

    let temp = slow.next;
    slow.next = null;
    return temp;
}

// Merge two sorted lists
function merge(a, b) {
    if (!a) return b;
    if (!b) return a;

    if (a.data < b.data) {
        a.next = merge(a.next, b);
        return a;
    } else {
        b.next = merge(a, b.next);
        return b;
    }
}

// Merge Sort
function mergeSort(head) {
    if (!head ||!head.next)
        return head;

    let second = split(head);

    head = mergeSort(head);
    second = mergeSort(second);

    return merge(head, second);
}

// Intersection using Sorting
function findIntersection(h1, h2) {

    // Sort both lists
    h1 = mergeSort(h1);
    h2 = mergeSort(h2);

    let dummy = new Node(-1);
    let tail = dummy;

    // Two pointer traversal
    while (h1 && h2) {

        if (h1.data < h2.data) {
            h1 = h1.next;
        }
        else if (h1.data > h2.data) {
            h2 = h2.next;
        }
        else {
            // Common element
            tail.next = new Node(h1.data);
            tail = tail.next;

            h1 = h1.next;
            h2 = h2.next;
        }
    }

    return dummy.next;
}

// Print list
function printList(head) {
    while (head) {
        console.log(head.data + " ");
        head = head.next;
    }
    console.log("\n");
}

// Main function
function main() {

    // List1: 9 -> 6 -> 4 -> 2 -> 3 -> 8
    let head1 = new Node(9);
    head1.next = new Node(6);
    head1.next.next = new Node(4);
    head1.next.next.next = new Node(2);
    head1.next.next.next.next = new Node(3);
    head1.next.next.next.next.next = new Node(8);

    // List2: 1 -> 2 -> 8 -> 6
    let head2 = new Node(1);
    head2.next = new Node(2);
    head2.next.next = new Node(8);
    head2.next.next.next = new Node(6);

    let result = findIntersection(head1, head2);

    console.log("Intersection: ");
    printList(result);
}

main();

Output
Intersection: 2 6 8 

[Expected Approach] Using Hashing – O(n + m) Time and O(m) Space

Store elements of the first list in a hash set. Then traverse the second list and check if each element exists in the set. Add to result while avoiding duplicates.

Algorithm:

  1. Create an empty Hash Set to store nodes in linkedList1 and initialize result as NULL.
  2. Traverse second list and insert all values into set
  3. Initialize tail as NULL and traverse first list
  4. If current value exists in set, it is common. Add it to result list
  5. Remove it from set to avoid duplicates and move to next node
  6. Return result list
C++
#include <iostream>
#include <unordered_set>
using namespace std;

// Node definition
class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = NULL;
    }
};

// hashing appraoch for Intersection of two linkedlist
Node* findIntersection(Node* head1, Node* head2) {

    unordered_set<int> st;

    // Store elements of second list
    Node* temp = head2;
    while (temp) {
        st.insert(temp->data);
        temp = temp->next;
    }

    Node* result = NULL;
    Node* tail = NULL;

    //Traverse first list
    while (head1) {

        // If common element found
        if (st.find(head1->data) != st.end()) {

            // Insert into result list
            if (!result) {
                result = tail = new Node(head1->data);
            } else {
                tail->next = new Node(head1->data);
                tail = tail->next;
            }

            // Remove to avoid duplicates
            st.erase(head1->data);
        }

        head1 = head1->next;
    }

    return result;
}

// Print function
void printList(Node* head) {
    while (head) {
        cout << head->data << " ";
        head = head->next;
    }
    cout << endl;
}

// Driver Code
int main() {

    // head1: 4 -> 2 -> 4 -> 1 -> 2 -> 8
    Node* head1 = new Node(4);
    head1->next = new Node(2);
    head1->next->next = new Node(4);
    head1->next->next->next = new Node(1);
    head1->next->next->next->next = new Node(2);
    head1->next->next->next->next->next = new Node(8);

    // head2: 2 -> 4 -> 6 -> 2 -> 4
    Node* head2 = new Node(2);
    head2->next = new Node(4);
    head2->next->next = new Node(6);
    head2->next->next->next = new Node(2);
    head2->next->next->next->next = new Node(4);

    Node* intersection = findIntersection(head1, head2);

    cout << "Intersection: ";
    printList(intersection);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Node definition
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// Function to create a new node
Node* createNode(int x) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = x;
    newNode->next = NULL;
    return newNode;
}

//hashing appraoch for Intersection of two linkedlist
Node* findIntersection(Node* head1, Node* head2) {
    bool* st = (bool*)calloc(100, sizeof(bool));
    int max_val = 0;

    //Store elements of second list
    Node* temp = head2;
    while (temp) {
        st[temp->data] = true;
        if (temp->data > max_val) max_val = temp->data;
        temp = temp->next;
    }

    Node* result = NULL;
    Node* tail = NULL;

    //Traverse first list
    while (head1) {
        // If common element found
        if (st[head1->data]) {
            // Insert into result list
            if (!result) {
                result = tail = createNode(head1->data);
            } else {
                tail->next = createNode(head1->data);
                tail = tail->next;
            }
            // Remove to avoid duplicates
            st[head1->data] = false;
        }
        head1 = head1->next;
    }
    free(st);
    return result;
}

// Print function
void printList(Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

// Driver Code
int main() {
    // head1: 4 -> 2 -> 4 -> 1 -> 2 -> 8
    Node* head1 = createNode(4);
    head1->next = createNode(2);
    head1->next->next = createNode(4);
    head1->next->next->next = createNode(1);
    head1->next->next->next->next = createNode(2);
    head1->next->next->next->next->next = createNode(8);

    // head2: 2 -> 4 -> 6 -> 2 -> 4
    Node* head2 = createNode(2);
    head2->next = createNode(4);
    head2->next->next = createNode(6);
    head2->next->next->next = createNode(2);
    head2->next->next->next->next = createNode(4);

    Node* intersection = findIntersection(head1, head2);

    printf("Intersection: ");
    printList(intersection);

    return 0;
}
Java
import java.util.HashSet;

// Node definition
class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

public class GfG {

    //hashing appraoch for Intersection of two linkedlist
    static Node findIntersection(Node head1, Node head2) {
        HashSet<Integer> st = new HashSet<>();

        //Store elements of second list
        Node temp = head2;
        while (temp!= null) {
            st.add(temp.data);
            temp = temp.next;
        }

        Node result = null;
        Node tail = null;

        //Traverse first list
        while (head1!= null) {
            // If common element found
            if (st.contains(head1.data)) {
                // Insert into result list
                if (result == null) {
                    result = tail = new Node(head1.data);
                } else {
                    tail.next = new Node(head1.data);
                    tail = tail.next;
                }
                // Remove to avoid duplicates
                st.remove(head1.data);
            }
            head1 = head1.next;
        }

        return result;
    }

    // Print function
    static void printList(Node head) {
        while (head!= null) {
            System.out.print(head.data + " ");
            head = head.next;
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {
        // head1: 4 -> 2 -> 4 -> 1 -> 2 -> 8
        Node head1 = new Node(4);
        head1.next = new Node(2);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(1);
        head1.next.next.next.next = new Node(2);
        head1.next.next.next.next.next = new Node(8);

        // head2: 2 -> 4 -> 6 -> 2 -> 4
        Node head2 = new Node(2);
        head2.next = new Node(4);
        head2.next.next = new Node(6);
        head2.next.next.next = new Node(2);
        head2.next.next.next.next = new Node(4);

        Node intersection = findIntersection(head1, head2);

        System.out.print("Intersection: ");
        printList(intersection);
    }
}
Python
from typing import Optional
from collections import OrderedDict

# Node definition
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# hashing appraoch for Intersection of two linkedlist
def findIntersection(head1, head2):

    st = OrderedDict()

    #Store elements of second list
    temp = head2
    while temp:
        st[temp.data] = None
        temp = temp.next

    result = None
    tail = None

    #Traverse first list
    while head1:

        # If common element found
        if head1.data in st:

            # Insert into result list
            if not result:
                result = tail = Node(head1.data)
            else:
                tail.next = Node(head1.data)
                tail = tail.next

            # Remove to avoid duplicates
            del st[head1.data]

        head1 = head1.next

    return result

# Print function
def printList(head):
    while head:
        print(head.data, end=" ")
        head = head.next
    print()

# Driver Code
head1 = Node(4)
head1.next = Node(2)
head1.next.next = Node(4)
head1.next.next.next = Node(1)
head1.next.next.next.next = Node(2)
head1.next.next.next.next.next = Node(8)

head2 = Node(2)
head2.next = Node(4)
head2.next.next = Node(6)
head2.next.next.next = Node(2)
head2.next.next.next.next = Node(4)

intersection = findIntersection(head1, head2)
print("Intersection: ", end="")
printList(intersection)
C#
using System;
using System.Collections.Generic;

// Node definition
public class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

public class Solution {

    //hashing appraoch for Intersection of two linkedlist 
    public static Node findIntersection(Node head1, Node head2) {

        HashSet<int> st = new HashSet<int>();

        //Store elements of second list
        Node temp = head2;
        while (temp != null) {
            st.Add(temp.data);
            temp = temp.next;
        }

        Node result = null;
        Node tail = null;

        //Traverse first list
        while (head1 != null) {

            if (st.Contains(head1.data)) {

                if (result == null) {
                    result = tail = new Node(head1.data);
                } else {
                    tail.next = new Node(head1.data);
                    tail = tail.next;
                }

                st.Remove(head1.data);
            }

            head1 = head1.next;
        }

        return result;
    }

    // Print function
    public static void printList(Node head) {
        while (head != null) {
            Console.Write(head.data + " ");
            head = head.next;
        }
        Console.WriteLine();
    }
}

public class Program {
    public static void Main() {

        // head1: 4 -> 2 -> 4 -> 1 -> 2 -> 8
        Node head1 = new Node(4);
        head1.next = new Node(2);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(1);
        head1.next.next.next.next = new Node(2);
        head1.next.next.next.next.next = new Node(8);

        // head2: 2 -> 4 -> 6 -> 2 -> 4
        Node head2 = new Node(2);
        head2.next = new Node(4);
        head2.next.next = new Node(6);
        head2.next.next.next = new Node(2);
        head2.next.next.next.next = new Node(4);

        Node intersection = Solution.findIntersection(head1, head2);

        Console.Write("Intersection: ");
        Solution.printList(intersection);
    }
}
JavaScript
/* Node definition */
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

/* hashing appraoch for Intersection of two linkedlistg */
function findIntersection(head1, head2) {
    const set = new Set();

    //Store elements of second list
    let temp = head2;
    while (temp) {
        set.add(temp.data);
        temp = temp.next;
    }

    let result = null;
    let tail = null;

    //Traverse first list
    while (head1) {

        // If common element found
        if (set.has(head1.data)) {

            // Insert into result list
            if (!result) {
                result = tail = new Node(head1.data);
            } else {
                tail.next = new Node(head1.data);
                tail = tail.next;
            }

            // Remove to avoid duplicates
            set.delete(head1.data);
        }

        head1 = head1.next;
    }

    return result;
}

/* Print function */
function printList(head) {
    let current = head;
    while (current) {
        console.log(current.data);
        current = current.next;
    }
}

/* Driver Code */
// head1: 4 -> 2 -> 4 -> 1 -> 2 -> 8
const head1 = new Node(4);
head1.next = new Node(2);
head1.next.next = new Node(4);
head1.next.next.next = new Node(1);
head1.next.next.next.next = new Node(2);
head1.next.next.next.next.next = new Node(8);

// head2: 2 -> 4 -> 6 -> 2 -> 4
const head2 = new Node(2);
head2.next = new Node(4);
head2.next.next = new Node(6);
head2.next.next.next = new Node(2);
head2.next.next.next.next = new Node(4);

const intersection = findIntersection(head1, head2);

console.log('Intersection:')
printList(intersection);

Output
Intersection: 4 2 

Time Complexity: O(m+n) , where m and n are number of elements present in first and second lists respectively.
Auxiliary Space: O(m), set stores elements of one list only

Comment