In-place Reversal of a Linked List: Introduction

Let’s go over the In-Place Manipulation of a Linked List pattern, its real-world applications, and some problems we can solve with it.

About the pattern

The in-place manipulation of a linked list pattern allows us to modify a linked list without using any additional memory. In-place refers to an algorithm that processes or modifies a data structure using only the existing memory space, without requiring additional memory proportional to the input size. This pattern is best suited for problems where we need to modify the structure of the linked list, i.e., the order in which nodes are linked together. For example, some problems require a reversal of a set of nodes in a linked list which can extend to reversing the whole linked list. Instead of making a new linked list with reversed links, we can do it in place without using additional memory.

The naive approach to reverse a linked list is to traverse it and produce a new linked list with every link reversed. The time complexity of this algorithm is O(n)O(n) while consuming O(n)O(n) extra space. How can we implement the in-place reversal of nodes so that no extra space is used? We iterate over the linked list while keeping track of three nodes: the current node, the next node, and the previous node. Keeping track of these three nodes enables us to efficiently reverse the links between every pair of nodes. This in-place reversal of a linked list works in O(n)O(n) time and consumes only O(1)O(1) space.

The following illustration demonstrates the in-place modification of a linked list by depicting the reversal of the given linked list: