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.
A1headAA1headBB1Inspect node links
| Node | Value | Next |
|---|---|---|
| A1 | 1 | A2 |
| A2 | 3 | A3 |
| A3 | 5 | null |
| B1 | 2 | B2 |
| B2 | 4 | B3 |
| B3 | 6 | null |
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
#include <cstddef>
struct Node {
int val;
Node* next;
Node(int value = 0, Node* link = nullptr)
: val(value), next(link) {}
};
Node* merge(Node* a, Node* b) {
Node dummy;
Node* tail = &dummy;
while (a && 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 ? a : b;
return dummy.next;
}