148. 排序链表

题目

插排法

为每个元素选择在其前面元素所构成的序列中最合适的位置:

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);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BeZer0

打赏一杯奶茶支持一下作者吧~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值