Leetcode148. 排序链表 -hot100

题目:


代码(首刷看解析 2024年3月5日):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (!head) return nullptr;
        vector<ListNode*> myvec;
        while (head) {
            myvec.push_back(head);
            head = head->next;
        }
        sort(myvec.begin(), myvec.end(), [](auto& a, auto& b){return a->val < b->val;});
        for (int i = 0; i < myvec.size(); ++i) {
            if(i != myvec.size() - 1) {
                myvec[i]->next = myvec[i + 1];
            } else {
                myvec[i]->next = nullptr;
            }
        }
        return myvec[0];
    }
};

代码(二刷debug on GPT,2024年9月5日)

auto cmp = [](ListNode* a, ListNode* b){
        return a->val > b->val;
};

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        priority_queue<ListNode*, vector<ListNode*>,decltype(cmp)> pq(cmp);
        auto cur = head;
        while(cur) {
            pq.push(cur);
            cur = cur->next;
        }
        auto dummyHead = new ListNode(0);
        cur = dummyHead;
        while(!pq.empty()) {
            cur->next = pq.top();
            pq.pop();
            cur = cur->next;
        }
        cur->next = nullptr;
        return dummyHead->next;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值