Sort a linked list in O(n log n) time using constant space complexity.

来源:互联网 发布:儿童安踏篮球鞋淘宝 编辑:程序博客网 时间:2024/05/17 23:14
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    static bool sort_by_value(const int &a,const int &b)
    {
        return a<b;
    }
    ListNode *sortList(ListNode *head)
    {
        vector<int> res;
        
        if(head == NULL)
            return head;
        ListNode *temp = head;
        while(temp != NULL)
        {
            res.push_back(temp->val);
            temp = temp->next;
        }
        sort(res.begin(),res.end());
        //sort(res.begin(),res.end().sort_by_value);
        
        temp = head;
        vector<int>::iterator iter = res.begin();
        while(temp != NULL)
        {
            temp->val = *iter;
            iter++;
            temp = temp->next;
        }
        return head;
    }      
};
1 0