Workspace

Problem workspace

3 day streakD

Merge Two Sorted Lists

EasyLinked ListsMerging & sorting

The challenge

Merge two sorted singly linked lists into one nondecreasing list, reusing their nodes.

Inputs are acyclic and share no nodes. Both are sorted in nondecreasing order.

Example

[1, 3, 5] + [2, 4, 6] → [1, 2, 3, 4, 5, 6].

Use the walkthrough below to inspect the input and each state change.

See Merge two lists, step by step

Follow the pointers. Watch each link change.

6 nodes · singly linkedIDs = node identity · ∅ = null
Interleaved values: Read the inputIDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links. Node positions stay fixed while arrows change. The pointer strip and node table below give the same state in text.head · headA1A13A25A3∅headB2B14B26B3∅
CurrentResultYellow arrow: changed next link
headA1headAA1headBB1
Inspect node links
Each row is a distinct node object. D is the dummy sentinel.
NodeValueNext
A11A2
A23A3
A35null
B12B2
B24B3
B36null
Step 01 / 8

Read the input

IDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links.

Start from the input head pointers.
View original input

A: 1 (A1) → 3 (A2) → 5 (A3); B: 2 (B1) → 4 (B2) → 6 (B3); parameters: {}

Parameter indices are zero-based, except n from the end, which is one-based. Node IDs remain fixed when links change.

Put it into code

A dummy head and output tail make every append the same operation.

Node stores val and next; the random-pointer lesson adds random. C++ uses C++17 or later.

class Node:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def merge(a, b):
    dummy = Node()
    tail = dummy
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a if a else b
    return dummy.next

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap