链表的排序----链表的归并排序
链表的归并排序(LinkList merge sort)
首先来看看如果有两条已序(sorted)的链表 ListNode *A , 和ListNode *B, 如何合并成一条已序的链表呢?
ListNode * mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *head = new ListNode(-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; return head->next; }
所以一条单链表的归并排序的思路如下: 同样是分治法
1.找到一条链表的中点节点,从中点节点断开成两条链表。
2.分别对前半部分链表和后半部分链表进行 链表的归并排序。
3.得到两部分已经排序的链表,最后进行归并链表
程序如下: leetcode accepted
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* sortList(ListNode* head) { if(head==nullptr|| head->next ==nullptr) return head; // get the len of the list ListNode * 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 two parts; ListNode *l1 = sortList(head); ListNode *l2 = sortList(slow); return mergeTwoLists(l1,l2); } ListNode * mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *head = new ListNode(-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; return head->next; } };