diff --git "a/2101040022/\346\216\222\345\272\217\351\223\276\350\241\250.cpp" "b/2101040022/\346\216\222\345\272\217\351\223\276\350\241\250.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..0009412e97409688c5257d8728cf58bc428a4d2b --- /dev/null +++ "b/2101040022/\346\216\222\345\272\217\351\223\276\350\241\250.cpp" @@ -0,0 +1,47 @@ +class Solution { +public: + ListNode* sortList(ListNode* head) { + if (!head || !head->next) { return head; } + ListNode* slow = head;//慢指针 + ListNode* fast = head;//快指针 + ListNode* precious = head; + while (fast && fast->next) { + precious = slow; + slow = slow->next; + fast = fast->next->next; + } + precious->next = NULL;//断开 + return merge(sortList(head), sortList(slow)); + } + // 或者可以这样写,无precious版本 + //ListNode* sortList(ListNode* head) { + // if (!head || !head->next) { return head; } + // ListNode* slow = head;//慢指针 + // ListNode* fast = head->next;//快指针 + // while (fast && fast->next) { + // slow = slow->next; + // fast = fast->next->next; + // } + // ListNode* right = slow->next; + // slow->next = NULL; + // return merge(sortList(head), sortList(right)); + //} + ListNode* merge(ListNode* list1, ListNode* list2) {// 合并两个链表模板 + if (list1 == NULL) { + return list2; + } + if (list2 == NULL) { + return list1; + } + + if (list1->val < list2->val) { + list1->next = merge(list1->next, list2); + return list1; + } + else { + list2->next = merge(list1, list2->next); + return list2; + } + } + +}; \ No newline at end of file