19. Remove Nth Node From End of List
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == NULL || head->next == NULL){
return NULL;
}
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *ptr1 = head;
ListNode *ptr2 = dummy;
for(int i=0; i<n-1; i++){
ptr1 = ptr1->next;
}
while(ptr1->next!=NULL){
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
ptr2->next = ptr2->next->next;
return dummy->next;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head==NULL)
return NULL;
ListNode *dummy = new ListNode(0);
dummy->next=head;
int num=0;
while(head!=NULL){
head=head->next;
num++;
}
head=dummy;
int i=0;
while(i<num-n){
head=head->next;
i++;
}
if(head->next!=NULL)
head->next=head->next->next;
return dummy->next;
}
};