您的位置:首页 > 其它

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

2017-03-17 00:14 405 查看
/**

 * 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;

    }      

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: