Partition List

Q:

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal tox.

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.

    ListNode *partition(ListNode *head, int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(!head)
            return NULL;
        ListNode* lessHead,*lessTail,*bigHead,*bigTail;
        lessHead = lessTail = bigHead = bigTail = NULL;
        
        ListNode* cur = head,*tmp;
        while(cur)
        {
            tmp = cur->next;
            if(cur->val<x)
            {
                if(bigTail)
                {
                    bigTail->next = cur->next;
                    cur->next = bigHead;   
                }
                    
                if(!lessTail)
                    lessHead = lessTail = cur;
                else{
                    lessTail->next = cur;
                    lessTail = cur;
                }
            }else
            {
                if(!bigHead)
                    bigHead = bigTail = cur;
                else
                    bigTail = cur;        
            }
            
            cur = tmp;
        }
        
        if(lessHead) return lessHead;
        else return bigHead;   
    }

  

posted @ 2013-09-16 10:57  summer_zhou  阅读(129)  评论(0编辑  收藏  举报