Skip to solution
easyDSA

How do you merge two sorted linked lists?

839 views
01

Understand the problem

Explain merging two sorted lists.

linked-list
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Use a dummy head and a tail pointer; repeatedly attach the smaller of the two list heads and advance it. When one list runs out, append the rest of the other. O(m+n) time, O(1) extra space. The dummy node avoids special-casing the head.

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

Dummy-head iterative merge
Run Playground
class ListNode:
    def __init__(self, val, nxt=None):
        self.val, self.next = val, nxt

def merge_two_lists(l1, l2):
    dummy = tail = ListNode(0)
    while l1 and l2:
        if l1.val <= l2.val:
            tail.next, l1 = l1, l1.next
        else:
            tail.next, l2 = l2, l2.next
        tail = tail.next
    tail.next = l1 or l2
    return dummy.next


# --- demo ---
def build(vals):
    head = None
    for v in reversed(vals): head = ListNode(v, head)
    return head
def to_list(head):
    out = []
    while head: out.append(head.val); head = head.next
    return out

print(to_list(merge_two_lists(build([1, 4]), build([2, 5]))))   # [1, 2, 4, 5]
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 10 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.

Back to track