Simple C++ solution using fast and slow pointers


#1
ListNode* Solution::removeNthFromEnd(ListNode* A, int B) {
    ListNode *slow=A,*fast=A,*prev=A;
    int flag=0;
    // advancing the fast pointer
    for(int i=0;i<B;i++){
        fast=fast->next;
        if(fast==NULL){
            flag=1;
            break;
        }
    }
    // checking if len is <B
    if(flag) return A->next;
    
    // finding nth from last
    while(fast){
        if(slow!=A) prev=prev->next;
        slow=slow->next;
        fast=fast->next;
    }
    prev->next=slow->next;
    return A;
}