源代码
/**
* 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* mergeTwoLists(ListNode *aPtr, ListNode *bPtr)
{
ListNode *p1 = aPtr, *p2 = bPtr;
ListNode *dummy = new ListNode(-1);
ListNode *p = dummy;
while (p1 != nullptr && p2 != nullptr)
{
if (p1->val > p2->val)
{
p->next = p2;
p2 = p2->next;
}
else
{
p->next = p1;
p1 = p1->next;
}
p = p->next;
}
if (p1 == nullptr) p->next = p2;
if (p2 == nullptr) p->next = p1;
return dummy->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* res;//最终返回的节点,记得初始化都得赋初值
for (size_t i = 0; i < lists.size(); ++i)
{
res = mergeTwoLists(res, lists[i]);
}
return res;
}
};
报错原因
Line 20: Char 21: runtime error: member access within misaligned address 0x000000000006 for type 'ListNode', which requires 8 byte alignment (solution.cpp)
0x000000000006: note: pointer points here
<memory cannot be printed>
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:29:21
在写这道链表的题目,发现这里报错,这是为啥呢,报错原因是因为没有赋初值,哪里没赋值呢,我这里写了一个mergeTwoLists()
的函数,其中有个res
,这个res
一开始没赋值,但是其每次都需要调用那个函数,导致报错,所以给res
赋值一个nullptr
初值则可以解决。
ListNode* res = nullptr;
轻松秒杀。