Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
Output : 1 -> 3 -> 5 -> 6 -> 4 -> 2 -> NULL
Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output : 1 -> 3 -> 5 -> 4 -> 2 -> NULL
Source: Microsoft Interview
Approach: A similar problem has been discussed in the given link, but there the even part was not reversed. Maintains two pointers odd and even for current nodes at odd and even positions respectively. Also store the first node of even linked list so that we can attach the even list at the end of the odd list after all odd and even nodes are connected together in two different lists. Once the even list has been separated, we just need to reverse it. Reversing a linked list can be found here. Once the even list is reverse, attach it to the odd linked list.
Below is the implementation of the above approach:
1 -> 3 -> 5 -> 6 -> 4 -> 2 -> NULL
- Given a linked list, reverse alternate nodes and append at the end
- Rearrange a linked list such that all even and odd positioned nodes are together
- Delete all odd or even positioned nodes from Circular Linked List
- Reverse alternate K nodes in a Singly Linked List
- Reverse nodes of a linked list without affecting the special characters
- Print the last k nodes of the linked list in reverse order | Recursive approach
- Print the last k nodes of the linked list in reverse order | Iterative Approaches
- Delete N nodes after M nodes of a linked list
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Linked List Sum of Nodes Between 0s
- Find the sum of last n nodes of the given Linked List
- Sum of all distinct nodes in a linked list
- Sum of the alternate nodes of linked list
- Sum of the nodes of a Circular Linked List
- Sum of the nodes of a Singly Linked List
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.