VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-two-sorted-linked-lists/

⇱ Merge two sorted linked lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge two sorted linked lists

Last Updated : 30 Aug, 2025

Given the heads of two sorted linked lists, merge them into a single sorted linked list and return the head of the merged list.

Examples:

Input:

👁 Input-1

Output: 2 -> 3 -> 5 -> 10 -> 15 -> 20 -> 40
Explanation: Merging two sorted lists [5, 10, 15, 40] and [2, 3, 20] in order gives 2 -> 3 -> 5 -> 10 -> 15 -> 20 -> 40.

👁 Output-1-

Input:

👁 Input-2-

Output: 1 -> 1 -> 2 -> 4
Explanation: Merging [1 ,1] and [2, 4] in order gives 1 -> 1 -> 2 -> 4.

👁 output-2

[Naive Approach] By Using Array - O((n+m) × log(n+m)) Time and O(n+m) Space

The idea is to use an array to store all the node data from both linked lists, sort the array, and then construct the resultant sorted linked list from the array elements.


Output
2 -> 3 -> 5 -> 10 -> 15 -> 20 -> 40

[Better Approach] Using Recursive Merge - O(n+m) Time and O(n+m) Space

The idea is to pick the smaller head node at each step and let recursion merge the remaining parts. if one list is empty, return the other; otherwise the smaller node becomes the next node in the merged list and its next is the recursive merge of the rest.

Algorithm:

  • If head1 is null, return head2.
  • If head2 is null, return head1.
  • Compare head1.data and head2.data.
  • If head1.data <= head2.data:
    => set head = head1
    => set head.next = merge(head1.next, head2)
    Else:
    => set head = head2
    => set head.next = merge(head1, head2.next)
  • Return head.

Output
2 -> 3 -> 5 -> 10 -> 15 -> 20 -> 40

[Efficient Approach] Using Iterative Merge - O(n+m) Time and O(1) Space

The idea is to iteratively merge two sorted linked lists using a dummy node to simplify the process. A current pointer tracks the last node of the merged list. We compare the nodes from both lists and append the smaller node to the merged list. Once one list is fully traversed, the remaining nodes from the other list are appended. The merged list is returned starting from the node after the dummy node.

Working:



Output
2 -> 3 -> 5 -> 10 -> 15 -> 20 -> 40
Comment