您的位置:首页 > 其它

链表排序(归并法)

2017-06-01 16:05 281 查看
1归并法

class ListNode {
public:
int val;
ListNode *next;
ListNode(int val) {
this->val = val;
this->next = NULL;
}
}


ListNode *sortList(ListNode *head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode *mid = findMid(head); //找中点
ListNode *right = sortList(mid->next);
mid->next = nullptr;           //从中间断开
ListNode *left = sortList(head);
return merge(left, right);
}
ListNode* findMid(ListNode* head) {
ListNode *slow = head;
ListNode *fast = head->next;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
ListNode* merge(ListNode* head1, ListNode* head2) {
ListNode dummy(-1);
ListNode* tail = &dummy;
while (head1 && head2) {
if (head1->val < head2->val) {
tail->next = head1;
head1 = head1->next;
}
else {
tail->next = head2;
head2 = head2->next;
}
tail = tail->next;
}
if (head1) {
tail->next = head1;
}
if (head2) {
tail->next = head2;
}
return dummy.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: