Union of two Linked Lists

Last Updated : 22 Oct, 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] Two Nested Loops - O(n * m) Time and O(n + m) Space

The idea is to traverse both linked lists and add each element to the result list only if it is not already present. Process the first list before the second to preserve the order of first occurrences.

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

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

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
// 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();
    }

    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
# Structure of Node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


# Function to check if value exists in result list
def isPresent(head, value):
    while head:
        if head.data == value:
            return True
        head = head.next
    return False


# Naive union
def makeUnion(head1, head2):
    result = None
    tail = None

    while head1:
        if not isPresent(result, head1.data):
            newNode = Node(head1.data)

            if result is None:
                result = tail = newNode
            else:
                tail.next = newNode
                tail = newNode

        head1 = head1.next

    while head2:
        if not isPresent(result, head2.data):
            newNode = Node(head2.data)

            if result is None:
                result = tail = newNode
            else:
                tail.next = newNode
                tail = newNode

        head2 = head2.next

    return result


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


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 = makeUnion(head1, head2)

    print("Union: ", end="")
    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();
    }

    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
class Node {
    constructor(x) {
        this.data = x;
        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) {
    const parts = [];
    while (head) {
        parts.push(head.data);
        head = head.next;
    }
    console.log(parts.join(" -> "));
}
// Driver code

//List 1: 9 -> 6 -> 4 -> 3 -> 8 
const 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 
const 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);

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

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

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

The idea is to use a set to keep track of elements that have already been added to the result list.

  • Create an empty result linked list and a set.
  • Traverse the first linked list. For each element, check whether it is present in the set.
  • If it is not present, add it to the set and append it to the result list.
  • Traverse the second linked list and perform the same check.
  • Append an element only if it is not already present in the set.
  • Return the result list.

By processing the first list before the second, the approach preserves the order of first occurrences and ensures that every element appears only once in the union.

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

    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()


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 = makeUnion(head1, head2)

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

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

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

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

        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)
        {
            Console.Write(head.data);
            if (head.next != null) Console.Write(" -> ");
            head = head.next;
        }
        Console.WriteLine();
    }

    static void 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);

        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

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

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