题目
插排法
为每个元素选择在其前面元素所构成的序列中最合适的位置:
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head)
return nullptr;
ListNode *p = head, *q = head->next;
while(q) { // 4,3
if(q->val < head->val) {
p->next = q->next;
q->next = head;
head = q;
q = p->next;
} // 2,4,1,3 // 1,2,4,3
else if(q->val < p->val) {
ListNode *h = head;
while(q->val > h->next->val)
h = h->next;
p->next = q->next;
q->next = h->next;
h->next = q;
q = p->next;
}
else {
p = q;
q = q->next;
}
}
return head;
}
};
归并排序
经典的归并排序链表模拟题:
class Solution {
public:
ListNode* merge_sort(ListNode *head, ListNode *tail) {
if(head->next == tail) {
head->next = nullptr;
return head;
}
else {
ListNode *slow = head, *fast = head;
while(fast != tail) {
slow = slow->next;
fast = fast->next;
if(fast != tail)
fast = fast->next;
}
return merge(merge_sort(head, slow), merge_sort(slow, tail));
}
}
ListNode* merge(ListNode *head1, ListNode *head2) {
ListNode *new_list = new ListNode(0), *temp = new_list, *temp1 = head1, *temp2 = head2;
while(temp1 != nullptr && temp2 != nullptr) {
if(temp1->val < temp2->val) {
temp->next = temp1;
temp1 = temp1->next;
}
else {
temp->next = temp2;
temp2 = temp2->next;
}
temp = temp->next;
}
if(temp1 != nullptr)
temp->next = temp1;
else if(temp2 != nullptr)
temp->next = temp2;
return new_list->next;
}
ListNode* sortList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
return merge_sort(head, nullptr);
}
};