标签:turn ret lis node while upload || head png
1.归
ListNode* sortList(ListNode* head) { if (head == nullptr || head->next == nullptr) return head; // 1.将待排序序列分为两部分 ListNode* pre = nullptr, *slow = head, *fast = head; while(fast != nullptr && fast->next != nullptr) { pre = slow; slow = slow->next; fast = fast->next->next; } pre->next = nullptr; // 2.对两个子部分再次进行划分 ListNode* l1 = sortList(head); ListNode* l2 = sortList(slow); // 3.合并 return merge(l1, l2); }
2.并
ListNode* merge(ListNode* l1, ListNode* l2) { ListNode* p = nullptr; if(l1->val < l2->val) { p = l1; l1 = l1->next; } else { p = l2; l2 = l2->next; } ListNode* l = p; while(l1 != nullptr && l2 != nullptr) { if(l1->val < l2->val) { p->next = l1; l1 = l1->next; } else { p->next = l2; l2 = l2->next; } p = p->next; } if (l1 != nullptr) p->next = l1; if (l2 != nullptr) p->next = l2; return l; }
标签:turn ret lis node while upload || head png
原文地址:https://www.cnblogs.com/qiang-wei/p/12274952.html