The error in line 15 is because you are trying to access a member variable val and next of a ListNode object a without initializing it. To fix the error, you need to create a new ListNode object and assign the value from the sorted forward_list to it. Here's the corrected code:

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        forward_list<int> l;
        for(auto i=head;i!=nullptr;i=i->next) l.emplace_front(i->val);
        l.sort();
        ListNode* dummy = new ListNode();
        ListNode* a = dummy;
        for(auto i=l.begin();i!=l.end();i++) {
            a->next = new ListNode(*i);
            a = a->next;
        }
        return dummy->next;
    }
};

Note that I've added a dummy ListNode at the beginning to simplify the implementation. The sorted list is stored starting from the next node of the dummy node, and the dummy node itself is not included in the final result


原文地址: https://www.cveoy.top/t/topic/iynn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录