My simple O(n) time C++ solution


  • 1
    Q
    ListNode* oddEvenList(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *p1 = head, *p2 = head->next, *evenHead = p2, *odd = p1;
        bool isOdd = true;
        while (p2) {
            p1->next = p2->next;
            p1 = p2;
            p2 = p2->next;
            isOdd = !isOdd;
            if (isOdd) odd = p1;
        }
        odd->next = evenHead;
        return head;
    }
    

Log in to reply
 

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