From 77d0c355b346f699bb5d3252c660d92c9c41d5bf Mon Sep 17 00:00:00 2001 From: Powfu <1875065753@qq.com> Date: Tue, 26 Dec 2023 13:05:05 +0000 Subject: [PATCH] =?UTF-8?q?add=202101040022/=E6=8E=92=E5=BA=8F=E9=93=BE?= =?UTF-8?q?=E8=A1=A8.cpp.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Powfu <1875065753@qq.com> --- ...2\345\272\217\351\223\276\350\241\250.cpp" | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 "2101040022/\346\216\222\345\272\217\351\223\276\350\241\250.cpp" 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 00000000..0009412e --- /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 -- Gitee