/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* split(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head->next;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* second = slow->next;
slow->next = nullptr;
return second;
}
ListNode* reverse(ListNode* head) {
ListNode* pre = NULL;
ListNode* node = head;
while(node) {
ListNode* nxt = node->next;
node->next = pre;
pre = node;
node = nxt;
}
return pre;
}
ListNode* merge(ListNode* h1, ListNode* h2) {
ListNode* dummy = new ListNode(-1);
ListNode* cur = dummy;
while(h1 != NULL && h2 != NULL) {
if(h1->val < h2->val) {
cur->next = h1;
h1 = h1->next;
} else {
cur->next = h2;
h2 = h2->next;
}
cur = cur->next;
}
return dummy->next;
}
ListNode* sortList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* mid = split(head);
ListNode* h1 = sortList(head);
ListNode* h2 = sortList(mid);
return merge(h1, h2);
}
};
10-24
1986
12-09