您的位置:首页 > 其它

148. Sort List -- 时间复杂度O(n log n)

2016-08-20 21:15 323 查看
Sort a linked list in O(n log n) time using constant space complexity.

归并排序

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

ListNode *sortList(ListNode *head) {
if (head==NULL || head->next == NULL){
return head;
}
//find the middle place
ListNode *p1=head, *p2=head->next;

while(p2 && p2->next){
p1 = p1->next;
p2 = p2->next->next;
}
p2 = p1->next;
p1->next = NULL;
return mergeTwoLists(sortList(head), sortList(p2));
}

ListNode *mergeTwoLists(ListNode* head1, ListNode* head2){
ListNode *p1 = head1,  *p2=head2;
static ListNode dummy(0);

ListNode *tail = &dummy;

while(p1 && p2){
if(p1->val < p2->val){
tail->next = p1;
p1 = p1->next;
}else{
tail->next = p2;
p2 = p2->next;
}
tail = tail->next;
}
if (p1) tail->next = p1;
if (p2) tail->next = p2;

return dummy.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: