Monday, November 25, 2013

LeetCode Problem : Partition List

Problem 


Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

Code

ListNode *partition(ListNode *head, int x) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if(!head)
        return head;
    ListNode *last,*tail;
    if(head->val < x){
        last = head;
        while(last->next && last->next->val < x)
            last = last->next;
        if(!last->next)
        return head;
        tail = last->next;
    }
    else{
        last = head;
        while(last->next && last->next->val >= x)
        last = last->next;
        if(!last->next)
            return head;
        tail = last->next;
        while(tail->next && tail->next->val < x)
            tail = tail->next;
        ListNode *tmp = head;
        ListNode *tmp1 = tail->next;
        head = last->next;
        tail->next = tmp;
        last->next = tmp1;
        last = tail;
        tail = tmp1;
    }
    while(tail){
        while(tail->next && tail->next->val >= x)
            tail = tail->next;
        if(!tail->next)
            return head;
        ListNode *front = tail->next;
        while(front->next && front->next->val < x)
            front = front->next;
        ListNode *tmp = last->next;
        ListNode *tmp1 = front->next;
        last->next = tail->next;
        front->next = tmp;
        tail->next = tmp1;
        last = front;
        tail = tmp1;
    }
    return head;
}

No comments:

Post a Comment