![](/img/trans.png)
[英]Runtime error in Linked List :member access within null pointer of type 'ListNode'
[英]runtime error: member access within null pointer of type 'ListNode'
我花了很多時間在上面,但仍然遇到同樣的錯誤。 請有人幫忙。 我已經為 leetcode 問題編寫了這段代碼。(合並兩個鏈表)已經閱讀了許多類似的答案,但仍然無法弄清楚
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode* third = NULL;
ListNode* last = NULL;
if (l1 && l2) {
if (l1->val < l2->val) {
third = last = l1;
l1 = l1->next;
last->next = NULL;
}
else {
third = last = l2;
l2 = l2->next;
last->next = NULL;
}
}
while (l1 && l2) {
if (l1->val < l2->val) {
last->next = l1;
last = l1;
l1 = l1->next;
last->next = NULL;
}
else {
last->next = l2;
last = l2;
l2 = l2->next;
last->next = NULL;
}
}
if (l1) {
last->next = l1;
}
if (l2) {
last->next = l2;
}
return third;
}
};
如果兩個輸入均非空,則僅將last
設置為非空值。
您需要先檢查它,例如
if (last)
{
last->next = l1 ? l1 : l2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.