/** * Definition for singly-linked list.
* struct ListNode {* int val;
* ListNode *next;
* ListNode (int x): Val (x), Next (NULL) {}};
*/void Mergelink (listnode* head,listnode* Mid, listnode* last) {listnode* head1=head;
listnode* End1 = mid;
listnode* rehead2 = mid->next;//records the end of the first list listnode* head2 = Mid->next,*end2 = last;
listnode* TEMP1,*TEMP2; while (HEAD1->NEXT!=REHEAD2) {while (head1->next!=rehead2 && head1->next->val<=head2->val
) {//When the first list is cloudy the second list is traversed head1=head1->next;
} if (Head1->next = = rehead2) {//When the first linked list to the tail is directly linked to the second list on the first list head1->next = head2;
Break
}else{Temp2 = head2->next;
Temp1 = head1->next;
Head1->next = head2;
Head2->next = Temp1;
Head2 = Temp2;
head1=head1->next; if (head2 = = End2) {//when the second linked list to the tail, find the end of the first list and then the second linked list to the end of the first linkThe tail while (head1->next!=rehead2) of the table Head1 = head1->next;
Head1->next = head2;
Break
}}}} void MergeSort (listnode* head,listnode* last) {listnode* fast = Head,*slow = head;
if (Head->next = = Last | | head->next->next==last) return;
while (Fast!=last && fast->next!=last) {//search for median fast=fast->next->next;
slow = slow->next;
} mergesort (Head,slow->next);
MergeSort (Slow,last);
Mergelink (head,slow,last);//merge two linked list return; } class Solution {public:listnode* sortlist (listnode* head) {if (Head==null | | head->next = NULL) return
Head
listnode* newhead = new ListNode (0);
Newhead->next = head;
MergeSort (NEWHEAD,NULLPTR);
Return newhead->next; }
};