Partition List

LeetCode #86


Description:

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.

Example:

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

Idea:

create two empty dummy head, one track the nodes less than x, one track the nodes greater or equal to x.

In the end, set the less pointer pointing to dummy2.next, set greaterEqual pointer pointing to NULL.

Code:

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode dummy1(-1);
        ListNode dummy2(-1);
        ListNode * less_ptr = &dummy1;
        ListNode * ge_ptr = &dummy2;

        for(ListNode *curr=head; curr!=NULL; curr=curr->next){
            if(curr->val<x){
                less_ptr->next=curr;
                less_ptr=less_ptr->next;
            }
            else{
                ge_ptr->next=curr;
                ge_ptr=ge_ptr->next;
            }
        }
        less_ptr->next=dummy2.next;
        ge_ptr->next=NULL; // This is important, otherwise could be loop

        return dummy1.next;
    }
};

results matching ""

    No results matching ""