LeetCode:執行出錯runtime error: member access within null pointer of type ‘ListNode‘ (solution.cpp)解決方法
阿新 • • 發佈:2021-01-21
以83.刪除排序連結串列中的重複元素為例:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* p = head;
while(p->next != NULL && p != NULL){
if(p->next->val == p->val){
ListNode* u = p->next;
p->next = u->next;
delete u;
}
else{
p = p->next;
}
}
return head;
}
};
提交上述程式碼,會顯示執行出錯:
runtime error: member access within null pointer of type ‘ListNode‘ (solution.cpp)
原因是引用了空指標,在&&中會先判斷左邊,要注意順序
while(p != NULL && p->next != NULL)
順利通過!