Problem Description: Given the head of a singly linked list, group all nodes at odd indices together followed by the nodes at even indices, and return the reordered list. The first node is considered odd, the second node is even, and so on. Preserve the relative order within both groups.
Examples:
Input: head = [1,2,3,4,5] Output: [1,3,5,2,4]
Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4]
Constraints:
Hints:
Explanation: To solve this problem, you can iterate through the linked list and separate the nodes at odd and even indices into two separate lists. Then, append the even list to the end of the odd list to get the final reordered list.
Here is a step-by-step approach:
odd and even, to represent the start of the odd and even linked lists, respectively.oddPtr and evenPtr, to the head of the original list.odd list and move oddPtr to the next node.even list and move evenPtr to the next node.odd list to the start of the even list.odd list, which is the reordered list.This approach ensures that the relative order within both the odd and even groups is preserved, and the problem constraints are satisfied.