progress

~/problems / Linked lists / Linked lists

Reverse Linked List

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Nodes are instances of the provided ListNode class (fields val and next). Write reverse_list(head) that reverses the list in place by re-pointing the next fields, and returns the new head. An empty list is None.

Don't create new nodes: the tests check that the nodes you return are the original ones. Lists can have 200,000 nodes, so a recursive solution will blow Python's recursion limit. ⭐ Bonus: a speed test with 200,000 nodes earns a star in O(n) time.

7 -> 3 -> 9        becomes   9 -> 3 -> 7
4                  becomes   4
(empty)            stays     (empty)
Show hint

Walk the list once, keeping track of the node before the current one; save the current node's next before you re-point it.

Topic: Linked lists. Dummy heads, pointer rewiring, fast/slow pointers.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc