




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.
1class ListNode:
2    def __init__(self, val=0, next=None):
3        self.val = val
4        self.next = next
5
6class Solution:
7    def oddEvenList(self, head: ListNode) -> ListNode:
8        if not head or not head.next:
9            return head
10
11        odd = head
12        even = head.next
13        evenHead = even
14
15        while even and even.next:
16            odd.next = even.next
17            odd = odd.next
18            even.next = odd.next
19            even = even.next
20        odd.next = evenHead
21        return headInitially, the function checks if the list is empty or a single node exists. 'odd' and 'even' pointers are initialized, with another pointer 'evenHead' remembering the even list's start. The loop iterates through nodes, connecting odd nodes and even nodes separately. In the end, the sequence of odd nodes is merged with the even section.
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.