How to Reverse a Linked List
Hey everyone, welcome to another article on Linked List. Till now we have covered various operations on linked list and in this article, we would be unraveling another operation on Linked List to understand this data structure in a much deeper way. The problem statement of this article is: How to Reverse a Linked List.
Algorithm for reversing a Linked List iteratively:
There can be a several approaches to solve this problem, but in this article we would be restricting ourselves to iterative approach.
1. Create three nodes, ‘prev’, ‘curr’ and ‘next’.
2. Assign:
·
‘prev’
as ‘NULL’
·
‘curr’
as ‘head’
·
‘next’
as ‘NULL’
3. Create a while loop with condition
curr not equal to null. In each iteration:
·
‘next’
is assigned with curr.next
·
‘curr’
is made to point towards ‘prev’
·
Assign
‘prev’ with ‘curr’
·
Assign
‘curr’ with ‘next’
4. After the while loop terminates the previous node, contains the head of the linked list.
Let's Implement this in the form of code: