AlgoViz

Reverse Linked List

Easy

Flip each next pointer as you walk

In simple words

Flip each arrow to point backward so the last box becomes the first — no boxes actually move.

The idea

Walk the list carrying a 'prev' pointer. At each node, remember the next node, point the current node back at prev, then advance both. prev ends up as the new head.

cur
1
2
3
4

Step 1 of 6. A linked list is boxes joined by arrows. To reverse it we flip every arrow to point backwards — no boxes move.

1/6
Optimal
timeO(n)spaceO(1)

Three pointers: prev, cur, next.

1let prev = null, cur = head;2while (cur) {3  const next = cur.next;4  cur.next = prev;5  prev = cur;6  cur = next;7}8return prev;

Input

list
[1, 2, 3, 4]

Memory

cur
= 0
next
prev
head

Output

new head

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
list = 1 -> 2 -> 3 -> 4
Output:
4 -> 3 -> 2 -> 1
Explanation:
All the arrows flip direction.

Example 2

Input:
list = 1 -> 2
Output:
2 -> 1
Explanation:
Two nodes swap ends.

Example 3

Input:
list = 7
Output:
7
Explanation:
A single node reverses to itself.

Finished the walkthrough? Add it to your streak.