问题描述
在O(n log n)的时间内使用常数级空间复杂度对链表进行排序。
解决方案
归并排序
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* findMiddle(ListNode* head){
ListNode* chaser = head;
ListNode* runner = head->next;
while(runner!=NULL && runner->next!=NULL){
chaser = chaser ->next;
runner = runner ->next->next;
}
return chaser;
}
ListNode* mergeList(ListNode* left,ListNode* right){
if(left == NULL)return right;
if(right == NULL)return left;
ListNode* dummy = new ListNode(0);
ListNode* newnode = dummy;
while(left!=NULL && right!=NULL){
if(left->val > right->val){
newnode->next = right;
right = right->next;
}
else{
newnode->next = left;
left = left->next;
}
newnode=newnode->next;
}
if(left == NULL){
newnode->next = right;
}
if(right == NULL){
newnode->next = left;
}
return dummy->next;
}
ListNode* sortList(ListNode* head){
if(head==NULL || head->next ==NULL)return head;
ListNode* middle = findMiddle(head);
ListNode* right = sortList(middle->next);
middle->next=NULL;
ListNode* left = sortList(head);
return mergeList(left,right);
}
};
这是别人的解决方案:
因为题目要求复杂度为O(nlogn),故可以考虑归并排序的思想。
归并排序的一般步骤为:
1)将待排序数组(链表)取中点并一分为二;
2)递归地对左半部分进行归并排序;
3)递归地对右半部分进行归并排序;
4)将两个半部分进行合并(merge),得到结果。
所以对应此题目,可以划分为三个小问题:
1)找到链表中点 (快慢指针思路,快指针一次走两步,慢指针一次走一步,快指针在链表末尾时,慢指针恰好在链表中点);
2)写出merge函数,即如何合并链表。 (见merge-two-sorted-lists 一题解析)
3)写出mergesort函数,实现上述步骤。