1. 程式人生 > 其它 >LeetCode:執行出錯runtime error: member access within null pointer of type ‘ListNode‘ (solution.cpp)解決方法

LeetCode:執行出錯runtime error: member access within null pointer of type ‘ListNode‘ (solution.cpp)解決方法

技術標籤:LeetCode連結串列leetcode

以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)
在這裡插入圖片描述

原因是引用了空指標,在&&中會先判斷左邊,要注意順序

將上述程式碼的第5行改為:

while(p != NULL && p->next != NULL)

順利通過!