O(n) time O(1) space - C solution


  • 0
    struct ListNode* oddEvenList(struct ListNode* head) {
        if(head == NULL || head->next == NULL)
        return head;
        
        struct ListNode* odd = head;
        struct ListNode* even = head->next;
        struct ListNode* current = even->next;
        struct ListNode* ptr1 = odd;
        struct ListNode* ptr2 = even;
        
        bool isOddPlace = true;
        
        while(current != NULL)
        {
            if(isOddPlace)
            {
              ptr1->next = current;
              ptr1 = current;
              isOddPlace = false;   
            }
            else
            {
              ptr2->next = current;
              ptr2 = current;
              isOddPlace = true;
            }
            current = current->next;
        }
        
        ptr1->next = even;
        ptr2->next = NULL;
        
        return head;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.