题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <cstddef> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head node * @return ListNode类 */ ListNode* sortInList(ListNode* head) { // write code here if(!head||!head->next) return head; ListNode* fast = head->next,*slow = head; while (fast&&fast->next) { slow = slow->next; fast = fast->next->next; } ListNode *tmp = slow->next; slow->next = NULL; ListNode *left = sortInList(head); ListNode *right = sortInList(tmp); ListNode *h = new ListNode(0); ListNode *res = h; while (left&&right) { if (left->val<right->val) { h->next = left; left = left->next; }else{ h->next = right; right = right->next; } h = h->next; } h->next = left ? left : right; return res->next; } };
思路复盘:SortInList对链表二分分解,while相当于递归,对链表进行合并