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
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
Aucun commentaire:
Enregistrer un commentaire