Wednesday, October 23, 2013

Partition List [Leetcode]

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.

Solution: first determine the relationship between the value of the head and x, say for example "less than"; then we scan the linked list; once we encounter an element which is not "less than" x, we add it to a dummy linked list. Thus, when we finish the scanning, we basically get two linked lists, one holds the elements "less than" x and the another one holds the elements not "less than" x; at the very last, we combine those two linked list together to get the final result.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(head==NULL) return NULL;
        bool relation = (head->val<x);
        ListNode* dummy = NULL;
        ListNode* curDummy = NULL;
        ListNode* curOrg = head;
        while(curOrg->next!=NULL){
            if((curOrg->next->val<x)!=relation){
                if(dummy==NULL){
                    dummy = curOrg->next;
                    curDummy = dummy;
                }
                else{
                    curDummy->next = curOrg->next;
                    curDummy = curDummy->next;
                }
                curOrg->next = curDummy->next;
                curDummy->next = NULL;
            }
            else
                curOrg = curOrg->next;
        }
        if(dummy==NULL || head->val<dummy->val){
            curOrg->next = dummy;
            return head;
        }
        curDummy->next = head;
        return dummy;
    }
};

No comments:

Post a Comment