Solution: Reverse Linked List
Let's solve the Reverse Linked List problem using the In-Place Manipulation of a Linked List pattern.
Statement
Given the head of a singly linked list, reverse the linked list and return its updated head.
Constraints:
Let n
be the number of nodes in a linked list.
-
n
-
Node.value
Solution
So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which one to follow based on considerations, such as time complexity and any implementation constraints.
Naive approach
The naive approach to solve the reverse linked list problem is to create a new linked list by traversing the original linked list in reverse order. To do this, we can copy the nodes of the original linked list into another data structure, for example, a stack. Then, we can pop the nodes from the stack one by one, creating a new linked list with each node we pop.
This approach has a time complexity of , since we need to iterate through the entire original list and then iterate through the stack. However, the space complexity is also , since we need to store all the nodes in the data structure. This means that if the original linked list is very large, we may run into memory issues. Overall, while this approach is simple to implement, it may not be the most efficient solution for large linked lists.
Optimized approach using in-place manipulation of a linked list
To reverse the entire linked list without occupying extra memory, we can utilize the in-place manipulation pattern. This pattern allows us to modify the directions of the nodes in the linked list directly by keeping track of the current, next, and previous nodes without the need for any additional data structures.
To reverse the linked list, we will follow these steps:
-
Initialize three pointers:
prev
,next
, andcurr
. Theprev
andnext
pointers are initialized as NULL, while thecurr
pointer is initialized to the head of the linked list. -
Iterate over the linked list. While iterating, perform the following steps:
- Before changing the next of
curr
, store the next node using the following line of codenext = curr->next
. - Now, we will update the
next
pointer ofcurr
with theprev
pointer. This will reverse the pointer of the current node from forward to backward, eventually aiding the reversal of the linked list. - After reversing the pointer, we’ll update
prev
ascurr
andcurr
asnext
usingprev = curr
andcurr = next
respectively.
- Before changing the next of
-
After reversing the whole linked list, we’ll change the head pointer to the
prev
pointer becauseprev
will be pointing to the new head node.
Let’s look at the following illustration to get a better understanding of reversing the linked list:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.