我的力扣算法148-排序链表

咳咳
看题吧
在这里插入图片描述
在这里插入图片描述
这道题有耍小聪明的解决思路,就是把链表中的值取出来,放在数组中,然后对数组使用sort排序,再转变为链表,这样子可以满足题目要求,但是这是小聪明,以后面试的时候不要耍这种小聪明,做面试题要将码徳,耗子尾汁,还有就是利用之前的快排的思想:

class Solution {
public:
    ListNode* sortList(ListNode* head) {
		ListNode* d=new ListNode;
        while(head){
            ListNode* p;
            p=d;
            while(p->next&&p->next->val<head->val)
            p=p->next;
            ListNode* q;
            q=head;
            head=head->next;
            q->next=p->next;
            p->next=q;
        }
        return d->next;
    }
};

到最后几个测试用例会导致超出时间限制。
这里使用的是归并排序的方式:

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        return sortList(head, nullptr);
    }

    ListNode* sortList(ListNode* head, ListNode* tail) {
        if (head == nullptr) {
            return head;
        }
        if (head->next == tail) {
            head->next = nullptr;
            return head;
        }
        ListNode* slow = head, *fast = head;
        while (fast != tail) {
            slow = slow->next;
            fast = fast->next;
            if (fast != tail) {
                fast = fast->next;
            }
        }
        ListNode* mid = slow;
        return merge(sortList(head, mid), sortList(mid, tail));
    }

    ListNode* merge(ListNode* head1, ListNode* head2) {
        ListNode* dummyHead = new ListNode(0);
        ListNode* temp = dummyHead, *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 dummyHead->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值