题目
思路
这个方法总共分为三步:
- 遍历链表将值获取到数组中 O(n) S(n)2. 排序数组 O(nlogn) (快排)3. 将数组元素按顺序写回链表 O(n)
题解
class Solution {
public:
void quickSort(vector<int> &arr, int front, int tail) {
if (front < tail) {
int l = front, r = tail, x = arr[front];
while (l < r) {
while (l < r && arr[r] > x) r--;
if (l < r) arr[l++] = arr[r];
while (l < r && arr[l] < x) l++;
if (l < r) arr[r--] = arr[l];
}
arr[l] = x;
quickSort(arr, front, l-1);
quickSort(arr, l+1, tail);
}
}
ListNode* sortList(ListNode* head) {
if (head == NULL) return head;
vector<int> arr;
ListNode *p = head;
while (p) {
arr.push_back(p->val);
p = p->next;
}
quickSort(arr, 0, arr.size()-1);
p = head;
for (int i = 0; i < arr.size(); i++) {
p->val = arr[i];
p = p->next;
}
}
return head;
}
};