6ms, beat 100%, O(1) space


  • 0
    Z
    class Solution {
    public:
        ListNode* partition(ListNode* head, int x) {
            ListNode* h = new ListNode(0);
            h->next = head;
            ListNode* p, *t = h;
            while(t->next != NULL && t->next->val < x) t = t->next;
            p = t->next;
            if(p==NULL) return head;
            while(p->next != NULL)
            {
                while(p->next != NULL && p->next->val >= x) p = p->next;
                if(p->next != NULL)
                {
                    ListNode* tmp = p->next;
                    p->next = p->next->next;
                    tmp->next = t->next;
                    t->next = tmp;
                    t = tmp;
                }
            }
            return h->next;
        }
    };

Log in to reply
 

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