Linked List In-place Reversal

Reverse a linked list, or a piece of one, by turning each next pointer around as you walk, using three pointers and no extra memory.

Overview

The idea

A singly linked list only points forward. To reverse it, each node's next must point to the node that came before it. Copying the values into an array and rebuilding the list works, but costs O(n) extra memory. In-place reversal changes the pointers themselves and needs only three variables.

There are three ways to get the reversed order, and they differ in memory and in what they keep. Copying the values to an array and rebuilding the list in reverse takes O(n) extra memory and n reads plus n writes, and it does not keep the original nodes. Pushing the nodes on a stack and popping them into a new order keeps the original nodes, but it still takes O(n) memory and touches nodes 2n times. Turning each next pointer around in place keeps the original nodes, touches each of the n nodes once, and needs only O(1) extra memory. That last one is the technique this chapter teaches.

The pointer trick is also the building block for harder problems: reverse a sublist, reverse in groups of k, check a palindrome, reorder a list.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio