题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head node * @return ListNode类 */ ListNode* sortInList(ListNode* head) { // write code here vector<int> data; ListNode* p = head; while(p != NULL) { data.push_back(p->val); p = p->next; } sort(data.begin(),data.end()); ListNode* prev = new ListNode(0); ListNode* ans = prev; for (auto it : data) { ListNode* cur = new ListNode(it); prev->next = cur; prev = cur; } return ans->next; } };