




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.
1public class ListNode {
2    public int val;
3    public ListNode next;
4    public ListNode(int x) { val = x; }
5}
6
7public class Solution {
8    public ListNode OddEvenList(ListNode head) {
9        if (head == null || head.next == null) return head;
10
11        ListNode odd = head;
12        ListNode even = head.next;
13        ListNode evenHead = even;
14
15        while (even != null && even.next != null) {
16            odd.next = even.next;
17            odd = odd.next;
18            even.next = odd.next;
19            even = even.next;
20        }
21        odd.next = evenHead;
22        return head;
23    }
24}C# implementation starts with a check for null or single-node list, returning as is. It initializes two pointers, 'odd' and 'even', and another 'evenHead' for remembering even node starts. Through looping, odd and even nodes are rearranged, and finally, the odd nodes' tail connects to the even starts, preserving order within the segregated lists.
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.