Union of two Linked Lists

Last Updated : 20 Apr, 2026

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

  • Each element should appear only once in the resulting list (no duplicates allowed).
  • The order of elements in the resulting list should be, all distinct nodes of the first list then remaining distinct nodes (nodes that are not in first) of the second list

Example:

Input: head1 = 9->6->4->3->8, head2 = 1->2->8->6->2

1fsd

Output: 9 -> 6 -> 4 -> 3 -> 8 -> 1 -> 2

dffdgghjkkljkl

Explanation: All distinct nodes of first list then remaining nodes (nodes that are not in first) of the second list

Input: head1 = 1->5->1->2->2->5, head2 = 4->5->6->7->1

sdfsdfsdf

Output: 1 -> 5 -> 2 -> 4 -> 6 -> 7

sfsdfsdfs

Explanation: All distinct nodes of first list then remaining nodes of the second list.

Try It Yourself
redirect icon

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

The idea is to build the union list by traversing both linked lists and adding elements only if they are not already present in the result. To check duplicates, we traverse the result list every time before inserting a new node.

Algorithm:

Initialize an empty result linked list. Traverse the first list:

  • For each node, check if it already exists in the result.
  • If not present, insert it at the end of the result.

Traverse the second list:

  • Again, check for each node if it exists in the result.
  • If not, insert it.

Return the final result list.

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

// Structure of Node
struct Node {
    int data;
    Node* next;
    
    Node(int x) {
        data = x;
        next = nullptr;
    }
};

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

// Naive union 
Node* makeUnion(Node* head1, Node* head2) {
    
    Node* result = nullptr;
    Node* tail = nullptr;
    
    while (head1) {
        if (!isPresent(result, head1->data)) {
            Node* newNode = new Node(head1->data);
            if (!result) result = tail = newNode;
            else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        head1 = head1->next;
    }
    
    while (head2) {
        if (!isPresent(result, head2->data)) {
            Node* newNode = new Node(head2->data);
            if (!result) result = tail = newNode;
            else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        head2 = head2->next;
    }
    
    return result;
}

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

// Driver Code
int main() {

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

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

    Node* unionList = makeUnion(head1, head2);

    cout << "Union: ";
    printList(unionList);

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

// Structure of Node
struct Node {
    int data;
    struct Node* next;
};

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

// Naive union 
struct Node* makeUnion(struct Node* head1, struct Node* head2) {
    struct Node* result = NULL;
    struct Node* tail = NULL;
    while (head1) {
        if (!isPresent(result, head1->data)) {
            struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
            newNode->data = head1->data;
            newNode->next = NULL;
            if (!result) result = tail = newNode;
            else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        head1 = head1->next;
    }
    while (head2) {
        if (!isPresent(result, head2->data)) {
            struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
            newNode->data = head2->data;
            newNode->next = NULL;
            if (!result) result = tail = newNode;
            else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        head2 = head2->next;
    }
    return result;
}

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

// Driver Code
int main() {
    // -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------
    struct Node* head1 = (struct Node*)malloc(sizeof(struct Node));
    head1->data = 9;
    head1->next = (struct Node*)malloc(sizeof(struct Node));
    head1->next->data = 6;
    head1->next->next = (struct Node*)malloc(sizeof(struct Node));
    head1->next->next->data = 4;
    head1->next->next->next = (struct Node*)malloc(sizeof(struct Node));
    head1->next->next->next->data = 3;
    head1->next->next->next->next = (struct Node*)malloc(sizeof(struct Node));
    head1->next->next->next->next->data = 8;
    // -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------
    struct Node* head2 = (struct Node*)malloc(sizeof(struct Node));
    head2->data = 1;
    head2->next = (struct Node*)malloc(sizeof(struct Node));
    head2->next->data = 2;
    head2->next->next = (struct Node*)malloc(sizeof(struct Node));
    head2->next->next->data = 8;
    head2->next->next->next = (struct Node*)malloc(sizeof(struct Node));
    head2->next->next->next->data = 6;
    head2->next->next->next->next = (struct Node*)malloc(sizeof(struct Node));
    head2->next->next->next->next->data = 2;
    struct Node* unionList = makeUnion(head1, head2);
    printf("Union: ");
    printList(unionList);
    return 0;
}
Java
import java.util.*;

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

public class GfG {

    // Function to check if value exists in result list
    public static boolean isPresent(Node head, int value) {
        while (head != null) {
            if (head.data == value)
                return true;
            head = head.next;
        }
        return false;
    }

    // Naive union 
    public static Node makeUnion(Node head1, Node head2) {
        Node result = null;
        Node tail = null;

        while (head1 != null) {
            if (!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;
        }

        while (head2 != null) {
            if (!isPresent(result, head2.data)) {
                Node newNode = new Node(head2.data);
                if (result == null) result = tail = newNode;
                else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            head2 = head2.next;
        }

        return result;
    }

    // Print Linked List
    public static void printList(Node head) {
        while (head != null) {
            System.out.print(head.data);
            if (head.next != null) System.out.print(" -> ");
            head = head.next;
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {

        // -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------
        Node head1 = new Node(9);
        head1.next = new Node(6);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(3);
        head1.next.next.next.next = new Node(8);

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

        Node unionList = makeUnion(head1, head2);

        System.out.print("Union: ");
        printList(unionList);
    }
}
Python
from typing import Optional

# Structure of Node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

    # Function to check if value exists in result list
    @staticmethod
    def isPresent(head: Optional['Node'], value: int) -> bool:
        while head:
            if head.data == value:
                return True
            head = head.next
        return False

    # Naive union 
    @staticmethod
    def makeUnion(head1: Optional['Node'], head2: Optional['Node']) -> Optional['Node']:
        result = None
        tail = None
        
        while head1:
            if not Node.isPresent(result, head1.data):
                newNode = Node(head1.data)
                if not result:
                    result = tail = newNode
                else:
                    tail.next = newNode
                    tail = newNode
            head1 = head1.next
        
        while head2:
            if not Node.isPresent(result, head2.data):
                newNode = Node(head2.data)
                if not result:
                    result = tail = newNode
                else:
                    tail.next = newNode
                    tail = newNode
            head2 = head2.next
        
        return result

    # Print Linked List
    @staticmethod
    def printList(head: Optional['Node']) -> None:
        while head:
            print(head.data, end='')
            if head.next:
                print(' -> ', end='')
            head = head.next
        print()


# Driver Code
if __name__ == "__main__":

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

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

    unionList = Node.makeUnion(head1, head2)

    print("Union: ", end='')
    Node.printList(unionList)
C#
using System;

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

public class GfG {

    // Function to check if value exists in result list
    public static bool IsPresent(Node head, int value) {
        while (head != null) {
            if (head.data == value)
                return true;
            head = head.next;
        }
        return false;
    }

    // Naive union 
    public static Node MakeUnion(Node head1, Node head2) {
        Node result = null;
        Node tail = null;
        
        while (head1 != null) {
            if (!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;
        }
        
        while (head2 != null) {
            if (!IsPresent(result, head2.data)) {
                Node newNode = new Node(head2.data);
                if (result == null) result = tail = newNode;
                else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            head2 = head2.next;
        }
        
        return result;
    }

    // Print Linked List
    public static void PrintList(Node head) {
        while (head != null) {
            Console.Write(head.data);
            if (head.next != null) Console.Write(" -> ");
            head = head.next;
        }
        Console.WriteLine();
    }

    // Driver Code
    public static void Main(string[] args) {

        // -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------
        Node head1 = new Node(9);
        head1.next = new Node(6);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(3);
        head1.next.next.next.next = new Node(8);
        
        // -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------
        Node head2 = new Node(1);
        head2.next = new Node(2);
        head2.next.next = new Node(8);
        head2.next.next.next = new Node(6);
        head2.next.next.next.next = new Node(2);
        
        Node unionList = MakeUnion(head1, head2);
        
        Console.Write("Union: ");
        PrintList(unionList);
    }
}
JavaScript
/* Structure of Node */
function Node(data) {
    this.data = data;
    this.next = null;
}

/* Function to check if value exists in result list */
function isPresent(head, value) {
    while (head) {
        if (head.data === value)
            return true;
        head = head.next;
    }
    return false;
}

/* Naive union */
function makeUnion(head1, head2) {
    let result = null;
    let tail = null;
    
    while (head1) {
        if (!isPresent(result, head1.data)) {
            const newNode = new Node(head1.data);
            if (!result) result = tail = newNode;
            else {
                tail.next = newNode;
                tail = newNode;
            }
        }
        head1 = head1.next;
    }
    
    while (head2) {
        if (!isPresent(result, head2.data)) {
            const newNode = new Node(head2.data);
            if (!result) result = tail = newNode;
            else {
                tail.next = newNode;
                tail = newNode;
            }
        }
        head2 = head2.next;
    }
    
    return result;
}

/* Print Linked List */
function printList(head) {
    let current = head;
    let result = '';
    while (current) {
        result += current.data;
        if (current.next) result += ' -> ';
        current = current.next;
    }
    console.log(result);
}

/* Driver Code */
(function main() {
    // -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------
    let head1 = new Node(9);
    head1.next = new Node(6);
    head1.next.next = new Node(4);
    head1.next.next.next = new Node(3);
    head1.next.next.next.next = new Node(8);
    
    // -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------
    let head2 = new Node(1);
    head2.next = new Node(2);
    head2.next.next = new Node(8);
    head2.next.next.next = new Node(6);
    head2.next.next.next.next = new Node(2);
    
    const unionList = makeUnion(head1, head2);
    
    console.log('Union:');
    printList(unionList);
})();

Output
Union: 9 -> 6 -> 4 -> 3 -> 8 -> 1 -> 2

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

The idea is to Use a hash set to keep track of unique elements. Traverse the first linked list and add unseen elements to both the set and result list. Then traverse the second list and insert only those elements that are not already present, ensuring no duplicates.

Algorithm:

  • Initialize a hash set and result list pointers.
  • Traverse first list and insert unique elements into set and result list.
  • Traverse second list and check each element in the set. Add only unseen elements to the result list, skip duplicates.
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;
    }
};

// Union using hashing 
Node* makeUnion(Node* head1, Node* head2) {
    
    unordered_set<int> seen;

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

    // Process first list
    while (head1) {
        if (seen.find(head1->data) == seen.end()) {
            seen.insert(head1->data);

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

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

    // Process second list
    while (head2) {
        if (seen.find(head2->data) == seen.end()) {
            seen.insert(head2->data);

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

            if (!result) result = tail = newNode;
            else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        head2 = head2->next;
    }

    return result;
}

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

// Driver Code
int main() {

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

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

    Node* unionList = makeUnion(head1, head2);

    cout << "Union: ";
    printList(unionList);

    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;
}

// Union using hashing 
Node* makeUnion(Node* head1, Node* head2) {
    bool seen[100] = {false};

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

    // Process first list
    while (head1) {
        if (!seen[head1->data]) {
            seen[head1->data] = true;

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

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

    // Process second list
    while (head2) {
        if (!seen[head2->data]) {
            seen[head2->data] = true;

            Node* newNode = createNode(head2->data);

            if (!result) result = tail = newNode;
            else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        head2 = head2->next;
    }

    return result;
}

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

// Driver Code
int main() {

    // -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------
    struct Node* head1 = createNode(9);
    head1->next = createNode(6);
    head1->next->next = createNode(4);
    head1->next->next->next = createNode(3);
    head1->next->next->next->next = createNode(8);

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

    struct Node* unionList = makeUnion(head1, head2);

    printf("Union: ");
    printList(unionList);

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

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

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

public class Main {

    // Union using hashing 
    static Node makeUnion(Node head1, Node head2)
    {

        HashSet<Integer> seen = new HashSet<>();

        Node result = null;
        Node tail = null;

        // Process first list
        while (head1 != null) {
            if (!seen.contains(head1.data)) {
                seen.add(head1.data);

                Node newNode = new Node(head1.data);

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

        // Process second list
        while (head2 != null) {
            if (!seen.contains(head2.data)) {
                seen.add(head2.data);

                Node newNode = new Node(head2.data);

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

        return result;
    }

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

    // Driver Code
    public static void main(String[] args)
    {

        Node head1 = new Node(9);
        head1.next = new Node(6);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(3);
        head1.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);
        head2.next.next.next.next = new Node(2);

        Node unionList = makeUnion(head1, head2);

        System.out.print("Union: ");
        printList(unionList);
    }
}
Python
# Node definition
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Union using hashing 


def makeUnion(head1, head2):
    seen = set()

    result = None
    tail = None

    # Process first list
    while head1:
        if head1.data not in seen:
            seen.add(head1.data)

            newNode = Node(head1.data)

            if not result:
                result = tail = newNode
            else:
                tail.next = newNode
                tail = newNode
        head1 = head1.next

    # Process second list
    while head2:
        if head2.data not in seen:
            seen.add(head2.data)

            newNode = Node(head2.data)

            if not result:
                result = tail = newNode
            else:
                tail.next = newNode
                tail = newNode
        head2 = head2.next

    return result

# Print function


def printList(head):
    while head:
        print(head.data, end="")
        if head.next:
            print(" -> ", end="")
        head = head.next
    print()


# Driver Code
head1 = Node(9)
head1.next = Node(6)
head1.next.next = Node(4)
head1.next.next.next = Node(3)
head1.next.next.next.next = Node(8)

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

unionList = makeUnion(head1, head2)

print("Union:", end=" ")
printList(unionList)
C#
using System;
using System.Collections.Generic;

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

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

    // Union using hashing 
    public static Node MakeUnion(Node head1, Node head2)
    {
        HashSet<int> seen = new HashSet<int>();

        Node result = null;
        Node tail = null;

        while (head1 != null) {
            if (!seen.Contains(head1.data)) {
                seen.Add(head1.data);

                Node newNode = new Node(head1.data);

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

        while (head2 != null) {
            if (!seen.Contains(head2.data)) {
                seen.Add(head2.data);

                Node newNode = new Node(head2.data);

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

        return result;
    }

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

    // Driver Code
    public static void Main(string[] args)
    {
        Node head1 = new Node(9);
        head1.next = new Node(6);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(3);
        head1.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);
        head2.next.next.next.next = new Node(2);

        Node unionList = MakeUnion(head1, head2);

        Console.Write("Union: ");
        PrintList(unionList);
    }
}
JavaScript
// Node definition
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Union using hashing
function makeUnion(head1, head2) {
    let seen = new Set();

    let result = null;
    let tail = null;

    // Process first list
    while (head1) {
        if (!seen.has(head1.data)) {
            seen.add(head1.data);

            let newNode = new Node(head1.data);

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

    // Process second list
    while (head2) {
        if (!seen.has(head2.data)) {
            seen.add(head2.data);

            let newNode = new Node(head2.data);

            if (!result) { result = tail = newNode; }
            else {
                tail.next = newNode;
                tail = newNode;
            }
        }
        head2 = head2.next;
    }

    return result;
}

// Print function
function printList(head) {
    while (head) {
        process.stdout.write(head.data.toString());
        if (head.next) { process.stdout.write(" -> "); }
        head = head.next;
    }
    console.log();
}

// Driver Code
// Driver Code

// -------- List 1 --------
let head1 = new Node(9);
head1.next = new Node(6);
head1.next.next = new Node(4);
head1.next.next.next = new Node(3);
head1.next.next.next.next = new Node(8);

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

let unionList = makeUnion(head1, head2);

process.stdout.write("Union: ");
printList(unionList);

Output
Union: 9 -> 6 -> 4 -> 3 -> 8 -> 1 -> 2
Comment