class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0);
ListNode* ptr1=head;
int count=0;
while(ptr1!=NULL){
count++;
ptr1=ptr1->next;
}
count=count-n;
ptr1=dummy;
while(count>0){
count--;
ptr1=ptr1->next; //getting error in this line
}
ptr1->next=ptr1->next->next;
return dummy->next;
}
};
1 Like
you assign prt1 to dummy with have size = 1 if your count > 1 then your ptr1 become null and you code try to extract next of null…
What the head value?
Initially ptr is pointing to a dummy node but dummy-> next is not defined and suppose list size is 5 and n=2 so final count will be 3 and second while loop will run 3 times and ptr will keep trying to access the next of nothing…so the program is giving this error…
For finding the nth node from end u can simply reverse the list and find nth node from beginning ,this will also be a good approach…