Problem: 148. 排序链表
解析
参考合并两个有序链表,那么需要做的只是把链表递归分为两半,然后合并两半即可,即归并排序,

slow和fast指针的使用可以找到要分割的点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class Solution { public: ListNode *sortList(ListNode *head) { return sortList(head, nullptr); } ListNode *sortList(ListNode *head, ListNode *tail) { if (head == nullptr) { return nullptr; } if(head->next==tail){ head->next=nullptr; return head; } ListNode *slow = head; ListNode *fast = head; while (fast != tail) { slow = slow->next; fast = fast->next; if (fast != tail) { fast = fast->next; } } return mergeTwoLists(sortList(head, slow), sortList(slow, tail)); } ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) { auto dummy = make_unique<ListNode>(-1); ListNode *node = dummy.get(); while (list1 != nullptr && list2 != nullptr) { if (list1->val <= list2->val) { node->next = list1; list1 = list1->next; node = node->next; } else { node->next = list2; list2 = list2->next; node = node->next; } } while (list1 != nullptr) { node->next = list1; list1 = list1->next; node = node->next; } while (list2 != nullptr) { node->next = list2; list2 = list2->next; node = node->next; } return dummy->next; } };
|