Sort a linked list in O(n log n) time using constant space complexity.
在O(nlogn)时间内,给一单向链表排序 分析,时间复杂度有要求,考虑用mergesort 取单向链表的中间元素:
ListNode* temp = head;//temp每次移动一步
ListNode* pre = head;
ListNode* last = head;//last每次移动两步
while(last != NULL && last->next != NULL){
pre = temp;
temp = temp->next;
last = last->next;
last = last->next;
}
pre->next = NULL;
//分成两个单向链表,head-pre和temp-last
代码如下:
/**
* 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 == NULL || head->next == NULL)
return head;
ListNode* temp = head;//temp每次移动一步
ListNode* pre = head;
ListNode* last = head;//last每次移动两步
while(last != NULL && last->next != NULL){
pre = temp;
temp = temp->next;
last = last->next;
last = last->next;
}
pre->next = NULL;
ListNode* right = sortList(temp);
ListNode* left = sortList(head);
return merge(left, right);
}
private:
ListNode* merge(ListNode* left, ListNode* right){
if(left == NULL)
return right;
if(right == NULL)
return left;
if(left->val < right->val){
left->next = merge(left->next, right);
return left;
}
else{
right->next = merge(left, right->next);
return right;
}
}
};