如果没有时间限制则使用插入排序进行的逻辑最简单,但是此题目限制了时间,于是我使用了一种投机的方法进行实现。
将数据取出来使用库函数实现。std::sort(a.begin(),a.end());
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
//这种投机取巧的方法我管他叫 数据重组处理法-将不好处理的数据变成好处理的数据处理
vector<int> nums;
while (head!=nullptr) {
nums.push_back(head->val);
head = head->next;
}
ListNode *re=new ListNode(0);
ListNode *m = re;
std::sort(nums.begin(),nums.end());
for (int a:nums) {
ListNode *it=new ListNode(a);
m->next = it;
m=m->next;
}
return re->next;
}
};