The merge sort of the linked list (linklist merge sort)
First of all, if there are two ordered (sorted) linked list ListNode *a, and ListNode *b, how to merge into an ordered list?
ListNode * mergetwolists (ListNode *l1, ListNode *L2) {ListNode*head =NewListNode (-1); ListNode*p =Head; for(;l1&&l2; p = p->next) { if(L1->val <l2->val) {P->next =L1; L1=l1->Next; } Else{p->next =L2; L2=l2->Next; }} P->next = l1!=nullptr?L1:l2; returnHead->Next; }
So the idea of a single-linked list is as follows: The same is the Division method
1. Find the midpoint node of a linked list and break it into two linked list from the point node.
2. The first half of the linked list and the second half of the list of linked list of the merge sort.
3. Get a list of two parts that have been sorted, and finally merge the linked list
The procedure is as follows: Leetcode accepted
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Sortlist (listnode*head) { if(head==nullptr| | Head->next ==nullptr)returnHead; //get the Len of the listListNode * Fast =Head; ListNode* Slow =Head; while(fast->next!=nullptr&&fast->next->next!=nullptr) {Fast= fast->next->Next; Slow= slow->Next; } Fast=slow; Find the mid of the linklist slow= slow->Next; Fast->next = nullptr;//cut the list to the parts;ListNode*L1 =Sortlist (head); ListNode*L2 =sortlist (slow); returnmergetwolists (L1,L2); } ListNode* Mergetwolists (ListNode *l1, ListNode *L2) {ListNode*head =NewListNode (-1); ListNode*p =Head; for(;l1&&l2; p = p->next) { if(L1->val <l2->val) {P->next =L1; L1=l1->Next; } Else{p->next =L2; L2=l2->Next; }} P->next = l1!=nullptr?L1:l2; returnHead->Next; } };
Sort----List of linked list by merge sort