Leetcode: Sort List

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


 

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    ListNode *sortList(ListNode *head) {

        // IMPORTANT: Please reset any member data you declared, as

        // the same Solution instance will be reused for each test case.

        if(head == NULL|| head->next == NULL)return head;

		map<int, vector<ListNode*>> mp;

        ListNode* pnode = head;

        while(pnode)

		{

			mp[pnode->val].push_back(pnode);

            pnode = pnode->next;

		}

		map<int, vector<ListNode*>>::iterator it = mp.begin();

		head = NULL;

		ListNode* cur = NULL;

		for(; it != mp.end(); it++)

		{

			vector<ListNode*> vec = (*it).second;

			for(int i = 0; i < vec.size(); i++)

			{

				if(head == NULL){

					head = vec[i];

					cur = vec[i];

				}else{

					cur->next = vec[i];

					cur = cur->next;

				}

			}

		}

		cur->next = NULL;

        return head;

    }

};


 


 

你可能感兴趣的:(LeetCode)