1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| #include <vector> #include <algorithm> #include <utility> using std::vector; using std::pair;
class Solution { public: ListNode *sortList(ListNode *head) { if (head == nullptr) return nullptr; vector<pair<int, ListNode *> > arr; int i, n; ListNode *p = head;
while (p) { arr.push_back({ p->val, p }); p = p->next; }
std::sort(arr.begin(), arr.end(), [](pair<int, ListNode *> &a, pair<int, ListNode *> &b) { return a.first < b.first; });
n = arr.size(); for (i = 0; i < n - 1; i++) { arr[i].second->next = arr[i + 1].second; } arr[n - 1].second->next = nullptr; return arr[0].second; } };
|