Problem Description
(Group all odd-indexed nodes together followed by even-indexed nodes in a singly linked list, preserving the relative order within each group.)
Key Insights
- Use two pointers: one for odd-indexed nodes and one for even-indexed nodes.
- The first node is considered odd, and the second node is even.
- Traverse the list once, reassigning the next pointers to segregate odd and even nodes.
- Finally, attach the even list at the end of the odd list.
- The solution must use O(1) extra space and O(n) time complexity.
Space and Time Complexity
Time Complexity: O(n) since the list is traversed once. Space Complexity: O(1) as only a few pointers are used.
Solution
Maintain two pointers, odd and even, starting from the head and head.next, respectively. As you iterate, update odd.next to point to the next odd element (skipping an even node) and even.next to point to the next even element. Once the end is reached, attach the even list to the end of the odd list. This in-place rearrangement preserves the initial ordering within odd and even groups while meeting the space and time constraints.