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
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.
- Reverse a Linked List in groups of given size | Set 2
- Reverse a doubly linked list in groups of given size
- Reverse a Linked List in groups of given size (Iterative Approach)
- Reverse a singly Linked List in groups of given size | Set 3
- Reverse a Linked List in groups of given size | Set 1
- Find N numbers such that a number and its reverse are divisible by sum of its digits
- Reverse String according to the number of words
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Check if a linked list is Circular Linked List
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Convert Singly Linked List to XOR Linked List
- Create new linked list from two given linked list with greater element at each node
- Reverse a Doubly Linked List
- Reverse alternate K nodes in a Singly Linked List
- Given a linked list, reverse alternate nodes and append at the end
- Merge two sorted linked lists such that merged list is in reverse order
- Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.