Odd Even Linked List¶

The objective is to group all the nodes with odd indices together followed by the nodes with even indices¶

The idea of the algorithm is to keep two list, even and odd and to add even node in even LinkedList and odd nodes in odd LinkedList wihout dealing with their child as these children will be updated in the future.¶
Only at the end it is important to set the child of the last node of the even LinkedList to None before grouping the even Linked List at the end of the odd Linked List (otherwise it could result in a loop in the Linked List)¶
In [ ]:
def oddEvenList(head: Optional[ListNode]) -> Optional[ListNode]:
    odd, even = ListNode(), ListNode()
    saved_odd, saved_even = odd, even

    
    i = 1 # index counter
    while head:
        # if index is even add to even and move even head
        if i % 2 == 0:
            even.next = head
            even = even.next
        else:
        # if index is even odd to odd and move odd head
            odd.next = head
            odd = odd.next
        
        # move head and increase index i
        head = head.next
        i += 1

    even.next = None # set even last element child to None to avoid getting a loop
    odd.next = saved_even.next # Group even Linked List at the end of the odd Linked List

    return(saved_odd.next)