C++, 5 lines of code


  • 0
    // split the original list to two separate lists and rejoin them at the end
    ListNode *partition(ListNode *head, int x) {
        ListNode dummy0(0), dummy1(0), *tails[2] = {&dummy0, &dummy1};
        for (auto p = head; p; p = p->next) tails[p->val >= x] = tails[p->val >= x]->next = p;
        tails[0]->next = dummy1.next;
        tails[1]->next = NULL;
        return dummy0.next;
    }
    

Log in to reply
 

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