




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    int val;
3    ListNode next;
4    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}The solution in Java checks first if the list is empty or only one element exists. Then, it assigns 'odd' and 'even' pointers to the first and second nodes. The 'evenHead' pointer captures the start of the even-nodes section. A loop traverses and repositions odd and even nodes separately. At the end, the tail of odd nodes is linked to the start of even nodes.
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.