Problem
Reverse a linked list.
Follow up 1 - Do it in-place and in one-pass.
Follow up 2 - Can you do it with only 2 pointers.
Examples
For example:
|
|
Solution
This is one of the famous interview question - can be solved iteratively and recursively. It becomes tricky, as in LinkedList we can go in forward direction. So, we need to understand some pointer basics when traversing and reversing the list.
Method 1 - Iterative Approach Using 3 Pointers and Variables
Algorithm
The following are the sequence of steps to be followed:
- Initially take three pointers: PrevNode, CurrNode, NextNode
- Let CurrNode point to HeaderNode of the list. And let PrevNode and NextNode points to null
- Now iterate through the linked list until CurrNode is null
- In the loop, we need to change NextNode to PrevNode, PrevNode to CurrNode and CurrNode to NextNode
Requires 3 temp variables.
Code
|
|
Dry Run - Visualization
Method 2 - Recursive Solution Using 1 Pointers
I personally prefer the non-recursive solution but it is always good to know both of them.
Algorithm
The following are the sequence of steps to be followed:
- If the list is empty, then the reverse of the list is also empty
- If the list has one element, then the reverse of the list is the element itself
- If the list has n elements, then the reverse of the complete list is reverse of the list starting from second node followed by the first node element. This step is recursive step
Visualization - Dry Run
The above mentioned steps can be described pictorially as shown below:
Code
|
|
Method 3 - Recursive Approach Passing 2 Pointers to Function
Another way is we can take 2 pointers - current ascurr
and previous as prev
. In each recursive call, we will keep on updating curr
to curr.next
, and prev
as well. At the end of recursion, we will set curr.next = prev
.
Code
|
|
Method 4 - Iteratively using Xor Approach
Another approach is to use xor approach, which is mentioned here.
To swap two variables without the use of a temporary variable,
|
|
fastest way is to write it in one line
|
|
Similarly, using two swaps
|
|
solution using xo
|
|
Solution in one line
|
|
The same logic is used to reverse a linked list.
|
|