题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <algorithm> #include <functional> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head node * @return ListNode类 */ ListNode* sortInList(ListNode* head) { // write code here vector<int> vec; ListNode* p = head; while (p) { vec.push_back(p->val); p = p->next; } sort(vec.begin(), vec.end(),greater<int>()); ListNode* c = nullptr; for (int i = 0; i < vec.size(); i++) { ListNode* temp = new ListNode(vec[i]); temp->next = c; c = temp; } return c; } };
思路: 链表存vector,调用vector中的sort排序,然后再放入链表