[leetcode]Partition List

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function 
        if(!head) return NULL;
        
        ListNode *lt = new ListNode(0);
        lt->next = head;
        ListNode *gt = new ListNode(0);
        
        ListNode *p = lt, *q = gt;
        
        while(p->next){
            if(p->next->val >= x){
                q->next = p->next;
                p->next = q->next->next;
                q = q->next;
                q->next = NULL;
                
            }else{
                p = p->next;
            }
        }
        
        p->next = gt->next;
        head = lt->next;
        
        delete lt;
        delete gt;
        
        return head;
    }
};


posted @ 2013-07-20 18:15  jlins  阅读(197)  评论(0编辑  收藏  举报