




Sponsored
Sponsored
This approach uses two pointers to manage odd and even indexed nodes separately. We maintain separate pointers for the head of the odd and even lists and iterate through the given list. As we go along, we link odd indices to the next odd and even indices to the next even. In the end, we connect the last odd indexed node to the head of the even indexed list.
Time Complexity is O(n) since we traverse the entire list once. Space Complexity is O(1) because we're rearranging pointers without using any extra space for storage.
1function ListNode(val, next) {
2    this.val = (val===undefined ? 0 : val)
3    this.next = (next===undefined ? null : next)
4}
5
6function oddEvenList(head) {
7    if (head === null || head.next === null) return head;
8
9    let odd = head;
10    let even = head.next;
11    let evenHead = even;
12
13    while (even !== null && even.next !== null) {
14        odd.next = even.next;
15        odd = odd.next;
16        even.next = odd.next;
17        even = even.next;
18    }
19    odd.next = evenHead;
20    return head;
21}JavaScript version checks initial conditions for a single or null list. Two primary pointers 'odd' and 'even' are responsibly placed at list start, with 'evenHead' used to track the start of even nodes. The while loop continues reorganizing the list, maintaining odd nodes connected first, then concluding by linking to the evenHead nodes, thereby achieving required order.
Although not typical due to O(1) space requirement, this problem could conceptually be solved recursively by defining a function that processes the head and its next elements recursively, managing pointers for odd and even segments. As recursion inherently uses extra space on the stack, this isn't space-optimal, thus academically interesting but not compliable with constant space constraints.
Time Complexity remains O(n) for full list traversal. However, Space Complexity rises to O(n) because of the call stack in recursion, unsuitable under given problem constraints for constant space.
1class ListNode:
2    def __init__(self, val=0, next
            
This Python solution uses a local function 'partition' which recursively treats nodes as alternating odd or even. Despite functional recursion achieving the same odd-even connection, it ruins constant space by occupying stack memory, which might exceed constraints under deep recursion.