Home > Back-end >  a program gives runtime error when submitted in leetcode but works in run code
a program gives runtime error when submitted in leetcode but works in run code

Time:08-17

encountered a question on leetcode
Question Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Example

1

here is my solution

    /**
 * 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* swapPairs(ListNode* head) {
       
        if(head->next->next==NULL)
        {   ListNode* temp=head;
            head=head->next;
            temp->next=NULL;

            head->next=temp;   //putting this line gives runtime error 
            
            
            return head;
        }
        
        
        else
        {   ListNode* temp=head;
            head=head->next;
            temp->next=head->next;
            head->next=temp;
            temp->next=swapPairs(temp->next);
            
           
            return head;
        }
        
    }
};

the code gives a runtime error when I put the marked line in the first condition but runs fine when using run code command. the error is
Line 15: Char 18: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:24:18

CodePudding user response:

If this program is passed a null pointer or a single node, an error will be thrown as a nullptr has no attributes (i.e next). Therefore head->next or head->next->next cannot be determined.

The solution is to check for these edge cases beforehand.

if(!head){
return head;
}else if(!(head->next)){
return head;
}
  • Related