Explanation: Alternative nodes in the given linked list are 4,1,5,4. Reversing the alternative nodes from the given list, and then appending them to the end of the list results in a list 10->9->3->9->4->5->1->4.
Single Pass In-place Extraction and Reverse of Alternate Nodes – O(n) Time and O(1) Space
The idea is to rearrange the linked list by maintaining two separate lists: one for the odd positioned nodes (which forms the main list) and another for the even positioned nodes. While traversing the linked list, treat it initially as the odd list. Whenever an even positioned node is encountered, remove it from the odd list and insert it at the front of the even list. Adding nodes at the front ensures that the even list is formed in reversed order without requiring a separate reversal step. After processing all the nodes, append the even list at the end of the odd list to obtain the final rearranged linked list.
Algorithm:
If the linked list has fewer than 3 nodes, return as no change is needed.
Initialize two pointers: odd (head) and even (second node).
Remove the first even node and start the even list with it.
Traverse the list and for each even node: Remove it from the main list and Insert it at the front of the even list (to reverse it)
Continue linking only odd nodes together during traversal.
After traversal, append the reversed even list at the end of the odd list.
Illustration:
Output
Linked list before calling rearrange() 1 2 3 4 5 6 7
Linked list after calling rearrange() 1 3 5 7 6 4 2
Time Complexity: O(n), The above code simply traverses the given linked list. So time complexity is O(n) Auxiliary Space: O(1), No extra space is required.