← All patterns

In-Place Linked List

Reverse, reorder, rotate, and partition linked lists by rewiring `next` pointers — O(1) space. Building blocks: dummy head, three-pointer reversal, head-insertion within a sublist, and the split-reverse-weave composition.

14 problems 4 Easy 9 Medium 1 Hard

Linked-list mutation in O(1) extra space. Patterns: three-pointer rotation for reversal (`prev`, `curr`, `next`), head-insertion within a sublist for sublist-reverse, the split-reverse-weave composition for reorder-list, and dummy-head sentinels for uniform splicing (so deleting the head needs no special case).

The list itself is the data structure — operations track only a handful of pointers.

When to reach for this pattern

  • Reverse, reorder, rotate, or partition a singly linked list
  • Operate on every k-th group of nodes
  • Remove or merge nodes by value or position
  • O(1) extra space is required (otherwise convert to array)

Canonical template

// three-pointer reverse
ListNode *prev = nullptr, *curr = head;
while (curr) {
    ListNode* nxt = curr->next;
    curr->next = prev;
    prev = curr;
    curr = nxt;
}
return prev;

// dummy-head splice for safe head deletion
ListNode dummy(0, head);
ListNode* pre = &dummy;
while (pre->next) {
    if (shouldRemove(pre->next)) pre->next = pre->next->next;
    else pre = pre->next;
}
return dummy.next;

C++ · adapt the names and types to your problem.

Common pitfalls

  • Losing the rest of the list by rewriting next before saving it
  • Forgetting a dummy head when the operation may delete or replace the original head
  • Off-by-one in 'kth from end' — gap pointer must start one step ahead
  • Forgetting to terminate the new last node with nullptr after splitting

Related patterns

Problems (14)

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.