题目描述:在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
1、先将链表中的数保存到vector向量中
2、使用sort()函数对vector向量进行排序
3、创建一个新的链表,将vector中的数压入链表中,返回新链表的phead指针
4、空间复杂度O(N),时间复杂度O(N),不符合题意
注意:链表为空,则直接返回;
/**
* 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) {
if(head == NULL) return head;
vector<int> nums;
ListNode* cur = head;
while(cur){
nums.push_back(cur->val);
cur = cur->next;
}
sort(nums.begin(),nums.end());
cur = new ListNode(NULL);
ListNode* phead = cur;
for(int i=0;i<nums.size();i++){
cur->val = nums[i];
if(i<nums.size()-1){
cur->next = new ListNode(NULL);
cur = cur->next;
}
}
return phead;
}
};