VOOZH about

URL: https://www.geeksforgeeks.org/dsa/union-and-intersection-of-two-linked-lists/

⇱ Union of two Linked Lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

[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.


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.

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