Article start
DSA Course: Interview Patterns and Problem Solving
Module 5: Linked List

Merge Two Sorted Lists: Dummy node Pattern

Use a dummy node and tail pointer to merge two sorted linked lists cleanly.

May 28, 2026·33

Learning Outcome

After this lesson, you should be able to merge two sorted linked lists by attaching the smaller current node to a result list.

Problem Statement

Given the heads of two sorted linked lists, merge them into one sorted linked list and return its head.

InputOutputWhy
1 -> 2 -> 4 and 1 -> 3 -> 41 -> 1 -> 2 -> 3 -> 4 -> 4Nodes are merged in nondecreasing order.

Brute Force Approach

Copy all values into an array, sort the array, and build a new linked list.

This works, but it wastes the fact that both lists are already sorted and uses extra space.

Optimized Approach

Use a dummy node before the answer and a tail pointer. Compare the current nodes of both lists, attach the smaller node to tail.next, then move that list forward.

When one list finishes, attach the remaining part of the other list directly.

Exact Pseudocode

dummy = new node
tail = dummy
while list1 is not null and list2 is not null:
  if list1.val <= list2.val:
    tail.next = list1
    list1 = list1.next
  else:
    tail.next = list2
    list2 = list2.next
  tail = tail.next
tail.next = list1 if list1 is not null else list2
return dummy.next

Reference Code

class Solution:
    def mergeTwoLists(self, list1, list2):
        dummy = ListNode(0)
        tail = dummy

        while list1 and list2:
            if list1.val <= list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next

        tail.next = list1 if list1 else list2
        return dummy.next

Sample Dry Run

list1list2Attachmerged
11list1's 11
21list2's 11 -> 1
2321 -> 1 -> 2
4331 -> 1 -> 2 -> 3
44Attach remaining1 -> 1 -> 2 -> 3 -> 4 -> 4

Complexity

MeasureValueReason
TimeO(n + m)Each node from both lists is visited once.
SpaceO(1)The nodes are reused; only pointers are stored.

Edge Cases

  • One list is empty.
  • Both lists are empty.
  • Duplicate values appear in both lists.

Interview Checklist

  • Use a dummy node to avoid special-casing the head.
  • Move tail after every attachment.
  • Attach the remaining list at the end.

FAQs

Why use a dummy node?

It gives a stable node before the answer so the first attachment uses the same logic as every later attachment.

Do we create new nodes?

The optimized version reuses existing nodes by changing links.

What is the core pattern?

Dummy node plus tail pointer.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.