You are given the 'head' of a singly linked list. Your task is to group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list’s head.
The first node is considered odd, and the second node is even, and so on.
Keep in mind that reordering is to be done according to the indexes and not the node values.
Also, ensure that the relative order inside both the even and odd groups should remain as it was in the input.
Input: 'head' -> 1 -> 3 -> 5 -> 7
Output: 'head' -> 1 -> 5 -> 3 -> 7
Explanation:
The nodes with odd indices (1, 5) are grouped together, followed by the nodes with even indices (3, 7).
The first line contains an integer 'n' - the size of the linked list.
The second line contains 'n' space-separated integers, denoting the nodes of the linked list.
Return the 'head' of the reordered linked list.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
5
2 4 6 8 10
2 6 10 4 8
The reordered list groups nodes with odd indices (2, 6, and 10) followed by nodes with even indices (4 and 8). So, the reordered list will look like: 2 -> 6 -> 10 -> 4 -> 8.
6
21 33 45 57 69 81
21 45 69 33 57 81
The reordered list groups nodes with odd indices (21, 45, and 69) followed by nodes with even indices (33, 57, and 81). Thus, the reordered list will appear as: 21 -> 45 -> 69 -> 33 -> 57 -> 81.
1 <= 'n' <= 5000
0 <= 'data' <= 10^4
Time Limit: 1 sec
Time Complexity : O(n)
Space Complexity : O(1)
Can we make two pointers and then merge them?
The idea is to maintain two pointers, one of which stores the list of nodes at odd positions and the other stores the list of nodes at an even position and then finally merge them.
The steps are as follows:
O(N), where ‘N’ is the size of the linked list.
We are just doing a linear traversal of the linked list. Hence, the final time complexity will be O(N).
O(1).
Since we are not using any extra space, the overall space complexity is O(1).