Reverse A Linked List
Approach: Iteration
It is possible to reverse a linked list by reversing the reference direction of the linked list. First, we take a prev
node and assign nullptr
to it. This pointer will be assigned as head node’s reference as it will become the last node in the linked list when the list is reversed.
Now, we start iterating over the linked list untill current != nullptr
. We take a temporary temp
node to store the reference of current->next
. To iterate, we move forward by assigning current
to prev
node and finally assign previously stored temp
to current
.
Lastly, we return the head prev
.
Above is the definition of a signly-linked-list.
Time complexity: $ O(n) $
Space Complexity: $ O(1) $
Approach: Recursive
Time complexity: $ O(n) $
Space complexity: $ O(n) $