Reverse a Linked List according to its Size
Given a linked list with n nodes, reverse it in the following way :
- If n is even, reverse it in group of n/2 nodes.
- If n is odd, keep the middle node as it is, reverse first n/2 elements and reverse last n/2 elements.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : 1 2 3 4 5 6 (n is even)
Output : 3 2 1 6 5 4
Input : 1 2 3 4 5 6 7 (n is odd)
Output : 3 2 1 4 7 6 5
Approach: The idea is similar to Reversing a linked list in groups of size k where k is n/2. Just need to check for mid node.
- If n is even, divide the linked list into two parts i.e. first n/2 elements and last n/2 elements and reverse both the parts.
- If n is odd, divide the linked list into three parts i.e. first n/2 elements, (n/2 + 1) th element and last n/2 elements and reverse both the parts except (n/2 + 1) th element .
Original List : 1 2 3 4 5 6 7 8 9 Reversed List : 4 3 2 1 5 9 8 7 6