Sort a linked list in O(n log n) time using constant space complexity.
使用mergeSort
class Solution {
public:
int listLen ( ListNode* head ) {
int len = 0;
while ( head ) { head = head->next; ++len; }
return len;
}
ListNode* merge ( ListNode* p, ListNode* q ) {
// 新建一个头结点为了方便以后的操作
ListNode* head = new ListNode ( -1 );
ListNode* res = head;
while ( p && q ) {
if ( p->val <= q->val ) {
head->next = p;
head = p;
p = p->next;
} else {
head->next = q;
head = q;
q = q->next;
}
}
head->next = ( p ? p : q );
head = res->next;
delete res; // 删除新建的头结点
return head;
}
ListNode* mergeSort ( ListNode *head, int len ) {
// 若只有只有元素直接返回
if ( len < 2 ) { return head; }
// 长度折半
int n = len >> 1, m = n;
ListNode* p = head, *q = head;
while ( n-- ) { p = q; q = q->next; }
p->next = NULL; // 断开两个部分
p = mergeSort ( head, m );
q = mergeSort ( q, len - m );
return merge ( p, q );
}
ListNode* sortList ( ListNode* head ) {
if ( head == NULL ) { return NULL; }
return mergeSort ( head, listLen ( head ) );
}
};