C++ simple Two pointer Approach for deleting Nth node from the end
/**
 * 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* removeNthFromEnd(ListNode* head, int n) {
        
        if(head ==NULL){
            return head;

        }
        ListNode *pseudo=new ListNode(0);
        pseudo->next=head;
        
        ListNode *slow=pseudo;
        ListNode *fast=pseudo;
        
        for(int i=0;i<n;i++){   // matalab fast waala phle hi n-element aage point kr rha hoga 
            fast=fast->next;

        }
        while(fast->next!=NULL){  //jab null hoga fast pointer to slow walla uss element ko point krega jisse                                                            //delete krna  hoga
            slow=slow->next;
            fast=fast->next;

        }
        slow->next=slow->next->next;  // deeltion ho gya 
        
        return pseudo->next; /// ye pseudo->next head ko return krega
            
        
    }
};
Comments (0)