C++ LeetCode 148: Sort List - Solution with Explanation and Correction
/**\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_listval 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.
原文地址: https://www.cveoy.top/t/topic/qfzI 著作权归作者所有。请勿转载和采集!