Here is my solution in C (one pass , 2 pointers) with comments


  • 6
    S
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode* HEAD1;
    struct ListNode* HEAD2;
    HEAD1=head;
    HEAD2=head;
    for(int i=0;i<n;i++) //take pointer HEAD1 n places ahead of HEAD2
    {   
        HEAD1=HEAD1->next;
        if(!HEAD1)          // when we have to delete the first node
        return head->next;
    }  
    while(HEAD1->next)   //take HEAD1 to last node so that HEAD2 is 1 behind the node we want to delete
    {   
        HEAD2=HEAD2->next;
        HEAD1=HEAD1->next;
        
    }
    HEAD2->next=HEAD2->next->next; // delete the node next to HEAD2
    
    
    return head;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.