I am working on LeetCode problem 19. Remove Nth Node From End of List:
Given the
headof a linked list, remove the nth node from the end of the list and return its head.Example 1:
Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]Constraints:
- The number of nodes in the list is
sz.1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
This is my code:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *p=head,*q=head,*t=NULL;
long long c=0;
while(p!=0){
c++;
p=p->next;
}
c=c-n;
while(q!=NULL && c>0){
t=q;
q=q->next;
c--;
}
t->next=q->next;
delete q;
return head;
}
};
I get this error when one of the test cases is run:
Line 26: Char 12: runtime error:
member access within null pointer of type 'ListNode' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:35:12
Not sure why I'm getting this error, because according to what I think, both t and q are not NULL here at the moment. So, I shouldn't have gotten this error.
ntimes to find the node you need to remove. Also worth making sure that some jerk doesn't give anlarger than the list.