排序链表

排序链表

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表

思路

刚开始用冒泡排序写的,但这个排序方法时间复杂度为O(n^2),leetcode上最后三个输入样例会超时,要用其他排序方法

代码

冒泡排序

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        int m=0;int len=1;
        ListNode* h=head;
        if(head==NULL){
            return head;
        }
        while(h->next!=NULL){
            h=h->next;
            len++;
        }
        h=head;
        for(int i=0;i<len;i++){
            for(int j=0;j<len-1;j++){
                if(h->val>h->next->val){
                    m=h->val;
                    h->val=h->next->val;
                    h->next->val=m;
                }
                h=h->next;
            }
            h=head;
        }
        return head;
    }
};

归并排序(时间复杂度为O(nlogn))

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head == NULL || head->next == NULL)return head;
        else
        {
            ListNode *fast = head,*slow = head;
            while(fast->next != NULL && fast->next->next != NULL)
            {
                fast = fast->next->next;
                slow = slow->next;
            }
            fast = slow;
            slow = slow->next;
            fast->next = NULL;
            fast = sortList(head);
            slow = sortList(slow);
            return merge(fast,slow);
        }
     ListNode* merge(ListNode *head1, ListNode *head2){
        if(head1 == NULL)return head2;
        if(head2 == NULL)return head1;
        ListNode* res;
        ListNode* p;
        if(head1->val < head2->val)
            {res = head1; head1 = head1->next;}
        else{res = head2; head2 = head2->next;}
        p = res;
         
        while(head1 != NULL && head2 != NULL)
        {
            if(head1->val < head2->val)
            {
                p->next = head1;
                head1 = head1->next;
            }
            else
            {
                p->next = head2;
                head2 = head2->next;
            }
            p = p->next;
        }
        if(head1 != NULL)p->next = head1;
        else if(head2 != NULL)p->next = head2;
        return res;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值