/**\n * Definition for singly-linked list.\n * struct ListNode {\n * \t int val;\n * \t ListNode next;\n * \t ListNode() : val(0), next(nullptr) {}\n * \t ListNode(int x) : val(x), next(nullptr) {}\n * \t ListNode(int x, ListNode next) : val(x), next(next) {}\n * };\n /\nclass Solution {\npublic:\n\tListNode sortList(ListNode head) {\n\t\tforward_list l;\n\t\tfor(auto i=head;i!=nullptr;i=i->next) l.emplace_front(i->val);\n\t\tl.sort();\n\t\tListNode dummy = new ListNode();\n\t\tListNode* a = dummy;\n\t\tfor(auto i=l.begin();i!=l.end();i++) {\n\t\t\ta->next = new ListNode(*i);\n\t\t\ta = a->next;\n\t\t}\n\t\treturn dummy->next;\n\t}\n};\n//第15行报错了内容: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:\n\ncpp\nclass Solution {\npublic:\n\tListNode* sortList(ListNode* head) {\n\t\tforward_list<int> l;\n\t\tfor(auto i=head;i!=nullptr;i=i->next) l.emplace_front(i->val);\n\t\tl.sort();\n\t\tListNode* dummy = new ListNode();\n\t\tListNode* a = dummy;\n\t\tfor(auto i=l.begin();i!=l.end();i++) {\n\t\t\ta->next = new ListNode(*i);\n\t\t\ta = a->next;\n\t\t}\n\t\treturn dummy->next;\n\t}\n};\n\n\nNote 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.

C++ LeetCode 148: Sort List - Solution with Explanation and Correction

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

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