# Javascript Program For Finding Intersection Of Two Sorted Linked Lists

Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory â€” the original lists should not be changed.Â

Example:Â

```Input:
Output: 2->4->6.
The elements 2, 4, 6 are common in
both the list so they appear in the
intersection list.

Input:
Output: 2->3->4
The elements 2, 3, 4 are common in
both the list so they appear in the
intersection list.```

Method: Using Dummy Node.Â
Approach:Â
The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’ and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists.Â

Below is the implementation of the above approach:

## Javascript

 `// Javascript program to implement  ``// the above approach `` `

Output:

```Linked list containing common items of a & b
2 4 6 ```

Complexity Analysis:Â

• 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 .
Please refer complete article on Intersection of two Sorted Linked Lists for more details!

Previous
Next