Walk the list with three pointers (prev, cursor, next). Save the forward link, flip cursor.next to point backward, then advance both pointers. The new head is prev when cursor reaches null.

Algorithm

Basic Implementation

basic.dart
class ListNode {
  int value;
  ListNode? next;
  ListNode(this.value, this.next);
}

void main() {
  final n5 = ListNode(5, null);
  final n4 = ListNode(4, n5);
  final n3 = ListNode(3, n4);
  final n2 = ListNode(2, n3);
  ListNode? head = ListNode(1, n2);

  ListNode? prev;
  ListNode? cursor = head;
  while (cursor != null) {
    final next = cursor.next;
    cursor.next = prev;
    prev = cursor;
    cursor = next;
  }
  head = prev;
}

The three-pointer loop saves the forward link, flips one next pointer, then advances prev and cursor.

Step 1 - Save the first forward link

prev starts at null, cursor is node(1), and nxt saves node(2).

Initial 1 -> 2 -> 3 -> 4 -> 5 chain with prev, cursor, and nxt named.prevcursornxtnullnode(1)node(2)node(3)node(4)node(5)

Step 2 - Flip node(1)

Set node(1).next to prev, making the reversed prefix 1 -> null.

After the first flip, prev points at node(1) and cursor advances to node(2).prevcursornode(1)nullnode(2)node(3)node(4)node(5)

Step 3 - Reversed prefix reaches 3

After three flips, the prefix is 3 -> 2 -> 1 -> null and cursor is node(4).

Middle of the reverse: prefix 3 -> 2 -> 1, suffix 4 -> 5.prevcursornode(3)node(2)node(1)nullnode(4)node(5)

Step 4 - Done

When cursor reaches null, prev is the new head: 5 -> 4 -> 3 -> 2 -> 1 -> null.

Final reversed list.headnode(5)node(4)node(3)node(2)node(1)null

Complexity

  • Time: O(n)
  • Space: O(1)

Implementation notes

  • Dart: do not allocate a new list. The reverse happens in place by flipping next pointers. cursor.next is nullable so the loop guard cursor != null doubles as the end-of-list check.
  • The replay shows prev, cursor, next plus the "reversed prefix" / "remaining suffix" view at every step, matching the lesson spec.
three-pointer rewire Each iteration captures the forward link, reverses one edge, then steps.