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.
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
- Reverse a Linked List in groups of given size | Set 2
- Reverse a Linked List in groups of given size | Set 1
- Reverse a doubly linked list in groups of given size
- Reverse a linked list
- Can we reverse a linked list in less than O(n)?
- Reverse a circular linked list
- Reverse a sublist of linked list
- Reverse first K elements of given linked list
- Reverse a Doubly Linked List | Set-2
- Reverse a Doubly Linked List
- Program to reverse a linked list using Stack
- Java Program for Reverse a linked list
- Reverse each word in a linked list node
- Print Reverse a linked list using Stack
- Reverse a Doubly linked list using recursion
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.