VOOZH about

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

⇱ Merge two sorted linked lists using Dummy Nodes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge two sorted linked lists using Dummy Nodes

Last Updated : 23 Jul, 2025

Given two sorted linked lists consisting of N and M nodes respectively. The task is to merge both of the lists (in place) and return the head of the merged list.

Examples:

Input: a: 5->10->15, b: 2->3->20
Output: 2->3->5->10->15->20

Input: a: 1->1, b: 2->4
Output: 1->1->2->4

The idea is to use a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy.Follow the below illustration for a better understanding:

👁 Merge-Two-Sorted-LinkedLists1

Follow the steps below to solve the problem:

  • First, make a dummy node for the new merged linked list
  • Now make two pointers, one will point to list1 and another will point to list2.
  • Now traverse the lists till one of them gets exhausted.
  • If the value of the node pointing to either list is smaller than another pointer, add that node to our merged list and increment that pointer.

Below is the implementation of the above approach: 


Output
Merged Linked List is: 
2 3 5 10 15 20 

Time Complexity: O(N + M), where N and M are the size of list1 and list2 respectively
Auxiliary Space: O(1)

Merge Two Sorted Linked Lists
Merge Two Sorted Linked Lists with O(1) Auxiliary Space

Comment
Article Tags:
Article Tags: