Open In App

Intersection of two Sorted Linked Lists

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given the head of two sorted linked lists, the task is to create a new linked list that represents the intersection of the two original lists. The new linked list should be created without modifying the original lists.

Note: The elements in the linked lists are not necessarily distinct.

Example: 

Input: head1 = 1->2->3->4->6, head2 = 2->4->6->8
Output: 2 4 6
Explanation: For the given two linked list, 2, 4 and 6 are the elements in the intersection.

Input: head1 = 10->20->40->50, head2 = 15->40
Output: 40

[Naive Approach] Using Nested loop – O(m*n) time and O(min(m, n)) space

The very basic idea is to use two nested loop. The outer loop iterates through the first linked list, picking each node one by one. For each node from the first list, the inner loop is used to search for the same value in the second linked list. If a match is found, the current node’s value is added to the result list. To avoid duplicates, a data structure (such as a set or a boolean array) is used to keep track of the visited nodes in the second list. This will make sure that a node is added to the result list only once. Once all the nodes in the first list have been processed, the resulting list containing the intersection of the two input lists is returned.

Complexity Analysis:

  • Time Complexity: O(m*n), where m and n are the lengths of the two input linked lists
  • Auxiliary Space: O(min(m, n)), due to storing the intersect linked list

[Expected Approach-1] Using Two Pointer – O(m + n) time and O(min(m, n)) space

Since the two linked lists are already sorted, we can efficiently find the elements that are common to both lists. We can do this by comparing the values of the nodes in the two lists as we go through them.

By comparing the node values, we can create a new linked list that contains only the elements that are present in both of the original lists. The main idea to doing this efficiently is to go through the two lists at the same time. During iteration, we can skip those elements that don’t match between the two lists, without needing to do unnecessary comparisons.

Below are the steps to implement the above intuition:

  • Initialization two pointers, p1 and p2 to the heads of the first and second linked lists, respectively.
  • Two additional pointers, head and tail, are used to build the resulting linked list that will contain the intersection of the two input lists. Initially, head and tail are set to NULL.
  • We use a loop to traverse both linked lists until we reach the end of either linked list.
    • At each step, we compare the current nodes pointed to by p1 and p2:
    • If p1->data is greater than p2->data, it means the current node in the second list is smaller, so we move the p2 pointer to the next node.
    • If p2->data is greater than p1->data, it means the current node in the first list is smaller, so we move the p1 pointer to the next node.
    • If p1->data and p2->data are equal, it means we have found a common element:
      • If the head pointer is NULL, we initialize the head of the intersection list with this node.
      • Otherwise, we append a new node with this value to the tail of the intersection list and update the tail pointer.
    • After processing a common element, both p1 and p2 pointers are moved to their next nodes.
  • The resulting linked list, starting from the head, represents the intersection of the two input lists.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int val)
    {
        data = val;
        next = NULL;
    }
};

Node* findIntersection(Node* head1, Node* head2)
{
    Node *p1 = head1, *p2 = head2;
    Node *head = NULL, *tail = NULL;

    // Traverse both linked lists and find the common nodes
    while (p1 && p2) {
        if (p1->data > p2->data) {

            // Nodes don't match, move to the next node in
            // the list with the smaller value
            p2 = p2->next;
        }
        else if (p2->data > p1->data) {

            // Nodes don't match, move to the next node in
            // the list with the smaller value
            p1 = p1->next;
        }
        else {

            // Nodes match, add the common node to the
            // intersection list
            if (head == NULL) {
                head = tail = new Node(p1->data);

                // Create a new head for the intersection
                // list
            }
            else {

                // Append the new node to the end of the
                // intersection list
                tail->next = new Node(p1->data);
                tail = tail->next;
            }

            // Move to the next nodes in both lists
            p1 = p1->next;
            p2 = p2->next;
        }
    }

    return head;
}

// Driver code
int main()
{
    // Create the first linked list
    Node* head1 = new Node(1);
    head1->next = new Node(2);
    head1->next->next = new Node(3);
    head1->next->next->next = new Node(4);
    head1->next->next->next->next = new Node(6);

    // Create the second linked list
    Node* head2 = new Node(2);
    head2->next = new Node(4);
    head2->next->next = new Node(6);
    head2->next->next->next = new Node(8);

    // Find the intersection of the two linked lists
    Node* result = findIntersection(head1, head2);

    // Print the intersection list
    while (result) {
        cout << result->data << " ";
        result = result->next;
    }
    cout << endl;

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

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

class Solution {
    public static Node findIntersection(Node head1,
                                        Node head2)
    {
        Node p1 = head1, p2 = head2;
        Node head = null, tail = null;

        // Traverse both linked lists and find the common
        // nodes
        while (p1 != null && p2 != null) {
            if (p1.data > p2.data) {
                // Nodes don't match, move to the next node
                // in the list with the smaller value
                p2 = p2.next;
            }
            else if (p2.data > p1.data) {
                // Nodes don't match, move to the next node
                // in the list with the smaller value
                p1 = p1.next;
            }
            else {
                // Nodes match, add the common node to the
                // intersection list
                if (head == null) {
                    head = tail = new Node(p1.data);
                    // Create a new head for the
                    // intersection list
                }
                else {
                    // Append the new node to the end of the
                    // intersection list
                    tail.next = new Node(p1.data);
                    tail = tail.next;
                }

                // Move to the next nodes in both lists
                p1 = p1.next;
                p2 = p2.next;
            }
        }

        return head;
    }

    public static void main(String[] args)
    {
        // Create the first linked list
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        head1.next.next.next = new Node(4);
        head1.next.next.next.next = new Node(6);

        // Create the second linked list
        Node head2 = new Node(2);
        head2.next = new Node(4);
        head2.next.next = new Node(6);
        head2.next.next.next = new Node(8);

        // Find the intersection of the two linked lists
        Node result = findIntersection(head1, head2);

        // Print the intersection list
        while (result != null) {
            System.out.print(result.data + " ");
            result = result.next;
        }
        System.out.println();
    }
}
Python
class Node:
    def __init__(self, val):
        self.data = val
        self.next = None


def findIntersection(head1, head2):
    p1, p2 = head1, head2
    head, tail = None, None

    # Traverse both linked lists and find the common nodes
    while p1 and p2:
        if p1.data > p2.data:
          
            # Nodes don't match, move to the next node in
            # the list with the smaller value
            p2 = p2.next
        elif p2.data > p1.data:
          
            # Nodes don't match, move to the next node in the
            # list with the smaller value
            p1 = p1.next
        else:
          
            # Nodes match, add the common node to the intersection list
            if not head:
                head = tail = Node(p1.data)
                
                # Create a new head for the intersection list
            else:
              
                # Append the new node to the end of the intersection list
                tail.next = Node(p1.data)
                tail = tail.next

            # Move to the next nodes in both lists
            p1 = p1.next
            p2 = p2.next

    return head


# Create the first linked list
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
head1.next.next.next = Node(4)
head1.next.next.next.next = Node(6)

# Create the second linked list
head2 = Node(2)
head2.next = Node(4)
head2.next.next = Node(6)
head2.next.next.next = Node(8)

# Find the intersection of the two linked lists
result = findIntersection(head1, head2)

# Print the intersection list
while result:
    print(result.data, end=" ")
    result = result.next
print()
Javascript
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class Solution {
    static findIntersection(head1, head2) {
        let p1 = head1, p2 = head2;
        let head = null, tail = null;

        // Traverse both linked lists and find the
        // common nodes
        while (p1 !== null && p2 !== null) {
            if (p1.data > p2.data) {
            
                // Nodes don't match, move to the
                // next node in the list with the smaller value
                p2 = p2.next;
            } else if (p2.data > p1.data) {
            
                // Nodes don't match, move to the next
                // node in the list with the smaller value
                p1 = p1.next;
            } else {
            
                // Nodes match, add the common node
                // to the intersection list
                if (head === null) {
                
                    // Create a new head for the
                    // intersection list
                    head = tail = new Node(p1.data); 
                } else {
                
                    // Append the new node to the end
                    // of the intersection list
                    tail.next = new Node(p1.data);
                    tail = tail.next;
                }

                // Move to the next nodes in both lists
                p1 = p1.next;
                p2 = p2.next;
            }
        }

        return head;
    }
}

// Create the first linked list
let head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(4);
head1.next.next.next.next = new Node(6);

// Create the second linked list
let head2 = new Node(2);
head2.next = new Node(4);
head2.next.next = new Node(6);
head2.next.next.next = new Node(8);

// Find the intersection of the two linked lists
let result = Solution.findIntersection(head1, head2);

// Print the intersection list
while (result !== null) {
    console.log(result.data + " ");
    result = result.next;
}

Output
2 4 6 

Time Complexity: O(m+n), where m and n are number of nodes in first and second linked lists respectively.
Only one traversal of the lists are needed.
Auxiliary Space: O(min(m, n)), The output list can store at most min(m,n) nodes.

[Expected Approach-2] Using Hashing – O(m + n) time and O(m) space

The main idea behind this approach is that hashing because this allow us constant-time searching and insertion operation. Using this properties of hashmap, we can efficiently identify the common elements between the two linked lists using.

Below are the steps to implement the above intuition:

  • Iterate through the first linked list and store the elements in a hashmap, along with their frequency (number of occurrences) in the first list.
  • Iterate through the second linked list and check if each element is present in the hashmap.
    • If an element is found, it means it is present in both lists, so we add it to the result linked list.
    • Decrement the frequency of the element in the hashmap. If the frequency becomes zero, we remove the element from the hashmap, as it has been used already.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Definition of a Node struct
struct Node {
    int data;
    Node* next;
    Node(int x) : data(x), next(nullptr)
    {
    }
};

// Function to find the intersection of two linked lists
Node* findIntersection(Node* head1, Node* head2)
{
    // Create a hash map to store the elements of the first
    // linked list
    unordered_map<int, int> set;

    // Create a dummy node to store the intersection
    Node* dummy = new Node(0);
    Node* curr = dummy;

    // Iterate through the first linked list and add each
    // element to the hash map
    while (head1 != nullptr) {
        set[head1->data]++;
        head1 = head1->next;
    }

    // Iterate through the second linked list
    while (head2 != nullptr) {

        // If the current element is present in the hash map
        if (set.count(head2->data)) {

            // Decrement the count of the element in the
            // hash map
            set[head2->data]--;

            // If the count becomes 0, remove the element
            // from the hash map
            if (set[head2->data] == 0) {
                set.erase(head2->data);
            }

            // Add the current element to the intersection
            // linked list
            curr->next = new Node(head2->data);
            curr = curr->next;
        }
        head2 = head2->next;
    }

    // Skip the dummy node and return the head of the
    // intersection linked list
    Node* result = dummy->next;
    delete dummy;
    return result;
}

int main()
{
    // Create the first linked list
    Node* head1 = new Node(1);
    head1->next = new Node(2);
    head1->next->next = new Node(3);
    head1->next->next->next = new Node(4);
    head1->next->next->next->next = new Node(6);

    // Create the second linked list
    Node* head2 = new Node(2);
    head2->next = new Node(4);
    head2->next->next = new Node(6);
    head2->next->next->next = new Node(8);

    // Find the intersection of the two linked lists
    Node* result = findIntersection(head1, head2);

    // Print the intersection list
    while (result != nullptr) {
        cout << result->data << " ";
        result = result->next;
    }
    cout << endl;

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

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

public class LinkedListIntersection {

    // Function to find the intersection of two linked lists
    public static Node findIntersection(Node head1,
                                        Node head2)
    {
        // Create a hash map to store the elements of the
        // first linked list
        HashMap<Integer, Integer> map = new HashMap<>();
        // Create a dummy node to store the intersection
        Node dummy = new Node(0);
        Node curr = dummy;

        // Iterate through the first linked list and add
        // each element to the hash map
        while (head1 != null) {
            map.put(head1.data,
                    map.getOrDefault(head1.data, 0) + 1);
            head1 = head1.next;
        }

        // Iterate through the second linked list
        while (head2 != null) {
            // If the current element is present in the hash
            // map
            if (map.containsKey(head2.data)) {
                // Decrement the count of the element in the
                // hash map
                map.put(head2.data,
                        map.get(head2.data) - 1);
                // If the count becomes 0, remove the
                // element from the hash map
                if (map.get(head2.data) == 0) {
                    map.remove(head2.data);
                }
                // Add the current element to the
                // intersection linked list
                curr.next = new Node(head2.data);
                curr = curr.next;
            }
            head2 = head2.next;
        }

        // Skip the dummy node and return the head of the
        // intersection linked list
        return dummy.next;
    }

    public static void main(String[] args)
    {
        // Create the first linked list
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        head1.next.next.next = new Node(4);
        head1.next.next.next.next = new Node(6);

        // Create the second linked list
        Node head2 = new Node(2);
        head2.next = new Node(4);
        head2.next.next = new Node(6);
        head2.next.next.next = new Node(8);

        // Find the intersection of the two linked lists
        Node result = findIntersection(head1, head2);

        // Print the intersection list
        while (result != null) {
            System.out.print(result.data + " ");
            result = result.next;
        }
        System.out.println();
    }
}
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


def find_intersection(head1, head2):
    # Create a hash map to store the elements of the first linked list
    elements = {}

    # Create a dummy node to store the intersection
    dummy = Node(0)
    curr = dummy

    # Iterate through the first linked list and add each element to the hash map
    while head1:
        elements[head1.data] = elements.get(head1.data, 0) + 1
        head1 = head1.next

    # Iterate through the second linked list
    while head2:
        # If the current element is present in the hash map
        if head2.data in elements:
            # Decrement the count of the element in the hash map
            elements[head2.data] -= 1
            # If the count becomes 0, remove the element from the hash map
            if elements[head2.data] == 0:
                del elements[head2.data]
            # Add the current element to the intersection linked list
            curr.next = Node(head2.data)
            curr = curr.next
        head2 = head2.next

    # Skip the dummy node and return the head of the intersection linked list
    return dummy.next


def print_list(head):
    while head:
        print(head.data, end=" ")
        head = head.next
    print()


# Create the first linked list
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
head1.next.next.next = Node(4)
head1.next.next.next.next = Node(6)

# Create the second linked list
head2 = Node(2)
head2.next = Node(4)
head2.next.next = Node(6)
head2.next.next.next = Node(8)

# Find the intersection of the two linked lists
result = find_intersection(head1, head2)

# Print the intersection list
print_list(result)
C#
using System;
using System.Collections.Generic;

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

public class LinkedListIntersection {

    // Function to find the intersection of two linked lists
    public static Node FindIntersection(Node head1,
                                        Node head2)
    {

        // Create a dictionary to store the elements of the
        // first linked list
        Dictionary<int, int> set
            = new Dictionary<int, int>();

        // Create a dummy node to store the intersection
        Node dummy = new Node(0);
        Node curr = dummy;

        // Iterate through the first linked list and add
        // each element to the dictionary
        while (head1 != null) {
            if (set.ContainsKey(head1.data)) {
                set[head1.data]++;
            }
            else {
                set[head1.data] = 1;
            }
            head1 = head1.next;
        }

        // Iterate through the second linked list
        while (head2 != null) {

            // If the current element is present in the
            // dictionary
            if (set.ContainsKey(head2.data)) {

                // Decrement the count of the element in the
                // dictionary
                set[head2.data]--;

                // If the count becomes 0, remove the
                // element from the dictionary
                if (set[head2.data] == 0) {
                    set.Remove(head2.data);
                }
                // Add the current element to the
                // intersection linked list
                curr.next = new Node(head2.data);
                curr = curr.next;
            }
            head2 = head2.next;
        }

        // Skip the dummy node and return the head of the
        // intersection linked list
        return dummy.next;
    }

    public static void Main(string[] args)
    {
        // Create the first linked list
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        head1.next.next.next = new Node(4);
        head1.next.next.next.next = new Node(6);

        // Create the second linked list
        Node head2 = new Node(2);
        head2.next = new Node(4);
        head2.next.next = new Node(6);
        head2.next.next.next = new Node(8);

        // Find the intersection of the two linked lists
        Node result = FindIntersection(head1, head2);

        // Print the intersection list
        while (result != null) {
            Console.Write(result.data + " ");
            result = result.next;
        }
        Console.WriteLine();
    }
}

Output
2 4 6 

Time Complexity: O(m + n), where m and n are the numbers of nodes in the two linked lists.
Auxiliary Space: O(m), primarily due to the hashmap.

[Other Approach] Using Recursion – O(m+n) time and O(min(m, n)) space

The recursive approach is very similar to the above two pointer approach. The idea is to compare the values of the current nodes in both lists and perform the following steps:

  • If the values are equal, we create a new node with the common value and recursively call the function on the remaining parts of both lists.
  • If the value in the first list is smaller, we move the pointer of the first list to the next node and recursively call the function.
  • If the value in the second list is smaller, we move the pointer of the second list to the next node and recursively call the function.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Definition of a Node struct
struct Node {
    int data;
    Node* next;
    Node(int x)
        : data(x)
        , next(NULL)
    {
    }
};

Node* findIntersection(Node* a, Node* b)
{

    // Base case: if either list is empty, the intersection
    // is also empty
    if (a == NULL || b == NULL) {
        return NULL;
    }

    // Recursive case
    if (a->data < b->data) {

        // The current node in the first list is smaller,
        // so we move to the next node in the first list
        return findIntersection(a->next, b);
    }
    else if (a->data > b->data) {

        // The current node in the second list is smaller,
        // so we move to the next node in the second list
        return findIntersection(a, b->next);
    }
    else {

        // The current nodes in both lists have the same
        // value, so we create a new node with this value
        // and recursively call the function on the
        // remaining parts of both lists
        Node* temp = new Node(a->data);
        temp->next = findIntersection(a->next, b->next);
        return temp;
    }
}

// Driver code
int main()
{

    // Create the first linked list
    Node* head1 = new Node(1);
    head1->next = new Node(2);
    head1->next->next = new Node(3);
    head1->next->next->next = new Node(4);
    head1->next->next->next->next = new Node(6);

    // Create the second linked list
    Node* head2 = new Node(2);
    head2->next = new Node(4);
    head2->next->next = new Node(6);
    head2->next->next->next = new Node(8);

    // Find the intersection of the two linked lists
    Node* result = findIntersection(head1, head2);

    // Print the intersection list
    while (result != NULL) {
        cout << result->data << " ";
        result = result->next;
    }

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

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

class Solution {
    public static Node findIntersection(Node a, Node b)
    {

        // Base case: if either list is empty, the
        // intersection is also empty
        if (a == null || b == null) {
            return null;
        }

        // Recursive case
        if (a.data < b.data) {

            // The current node in the first list is
            // smaller, so we move to the next node in the
            // first list
            return findIntersection(a.next, b);
        }
        else if (a.data > b.data) {

            // The current node in the second list is
            // smaller, so we move to the next node in the
            // second list
            return findIntersection(a, b.next);
        }
        else {

            // The current nodes in both lists have the same
            // value, so we create a new node with this
            // value and recursively call the function on
            // the remaining parts of both lists
            Node temp = new Node(a.data);
            temp.next = findIntersection(a.next, b.next);
            return temp;
        }
    }

    public static void main(String[] args)
    {
        // Create the first linked list
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        head1.next.next.next = new Node(4);
        head1.next.next.next.next = new Node(6);

        // Create the second linked list
        Node head2 = new Node(2);
        head2.next = new Node(4);
        head2.next.next = new Node(6);
        head2.next.next.next = new Node(8);

        // Find the intersection of the two linked lists
        Node result = findIntersection(head1, head2);

        // Print the intersection list
        while (result != null) {
            System.out.print(result.data + " ");
            result = result.next;
        }
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


def findIntersection(a, b):

    # Base case: if either list is empty, the intersection is also empty
    if a is None or b is None:
        return None

    # Recursive case
    if a.data < b.data:

        # The current node in the first list is smaller, so we move to
        # the next node in the first list
        return findIntersection(a.next, b)
    elif a.data > b.data:

        # The current node in the second list is smaller, so we move
        # to the next node in the second list
        return findIntersection(a, b.next)
    else:

        # The current nodes in both lists have the same value,
        # so we create a new node with this value and recursively
        # call the function on the remaining parts of both lists
        temp = Node(a.data)
        temp.next = findIntersection(a.next, b.next)
        return temp


# Create the first linked list
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
head1.next.next.next = Node(4)
head1.next.next.next.next = Node(6)

# Create the second linked list
head2 = Node(2)
head2.next = Node(4)
head2.next.next = Node(6)
head2.next.next.next = Node(8)

# Find the intersection of the two linked lists
result = findIntersection(head1, head2)

# Print the intersection list
while result:
    print(result.data, end=" ")
    result = result.next
print()
C#
public class Node {
    public int data;
    public Node next;

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

public class Solution {
    public static Node findIntersection(Node a, Node b)
    {
        // Base case: if either list is empty, the
        // intersection is also empty
        if (a == null || b == null) {
            return null;
        }

        // Recursive case
        if (a.data < b.data) {
            // The current node in the first list is
            // smaller, so we move to the next node in the
            // first list
            return findIntersection(a.next, b);
        }
        else if (a.data > b.data) {
            // The current node in the second list is
            // smaller, so we move to the next node in the
            // second list
            return findIntersection(a, b.next);
        }
        else {
            // The current nodes in both lists have the same
            // value, so we create a new node with this
            // value and recursively call the function on
            // the remaining parts of both lists
            Node temp = new Node(a.data);
            temp.next = findIntersection(a.next, b.next);
            return temp;
        }
    }

    public static void Main(string[] args)
    {
        // Create the first linked list
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        head1.next.next.next = new Node(4);
        head1.next.next.next.next = new Node(6);

        // Create the second linked list
        Node head2 = new Node(2);
        head2.next = new Node(4);
        head2.next.next = new Node(6);
        head2.next.next.next = new Node(8);

        // Find the intersection of the two linked lists
        Node result = findIntersection(head1, head2);

        // Print the intersection list
        while (result != null) {
            System.Console.Write(result.data + " ");
            result = result.next;
        }
    }
}
Javascript
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

function findIntersection(a, b) {

    // Base case: if either list is empty, the intersection is also empty
    if (a === null || b === null) {
        return null;
    }

    // Recursive case
    if (a.data < b.data) {
    
        // The current node in the first list is smaller,
        // so we move to the next node in the first list
        return findIntersection(a.next, b);
    } else if (a.data > b.data) {
    
        // The current node in the second list is smaller,
        // so we move to the next node in the second list
        return findIntersection(a, b.next);
    } else {
    
        // The current nodes in both lists have the same value,
        // so we create a new node with this value and recursively
        // call the function on the remaining parts of both lists
        let temp = new Node(a.data);
        temp.next = findIntersection(a.next, b.next);
        return temp;
    }
}

// Create the first linked list
let head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(4);
head1.next.next.next.next = new Node(6);

// Create the second linked list
let head2 = new Node(2);
head2.next = new Node(4);
head2.next.next = new Node(6);
head2.next.next.next = new Node(8);

// Find the intersection of the two linked lists
let result = findIntersection(head1, head2);

// Print the intersection list
while (result !== null) {
    console.log(result.data, end=" ");
    result = result.next;
}
console.log();

Output
2 4 6 

Time Complexity: O(m+n), as each node is processed once.
Auxiliary Space: O(min(m, n)), where m is the number of nodes in the first list and n is the number of nodes in the second list, due to the recursion stack.



Next Article

Similar Reads