放到数组里排序就行了
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int a[50010]; ListNode* sortList(ListNode* head) { if (head == nullptr) return head; ListNode* p = head; int cnt = 0; while(p != nullptr) { a[cnt++] = p->val; p = p->next; } sort(a, a + cnt); p = head; cnt = 0; while(p != nullptr) { p->val = a[cnt++]; p = p->next; } return head; } };