/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <climits>
class Solution {
public:
ListNode *mergeList(ListNode *head1, ListNode *head2){
ListNode tmp(0);
ListNode *newHead = &tmp, *curH1 = head1, *curH2 = head2;
while (curH1 && curH2) {
if (curH1->val < curH2->val) {
newHead->next = curH1;
curH1 = curH1->next;
} else {
newHead->next = curH2;
curH2 = curH2->next;
}
newHead = newHead->next;
}
if (curH1) {
newHead->next = curH1;
}
if (curH2) {
newHead->next = curH2;
}
return tmp.next;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode *slow = head, *fast = slow->next;
//查找链表中点
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *tmp = slow->next;
slow->next = nullptr;
ListNode *head1 = sortInList(head);
ListNode *head2 = sortInList(tmp);
ListNode *newHead = mergeList(head1, head2);
return newHead;
}
};