Leetcode Remove Nth Node From End of List problem solution in C++ programming

In the Leetcode Remove Nth Node From End of List problem solution in C++ programming Given the head of a linked list, remove the nth node from the end of the list and return its head.

Leetcode Remove Nth Node From End of List problem solution in C++ programming

ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(!head){return nullptr;}
        ListNode * runner, * current;
        current = runner = head;
        int count = 0;
        while(runner){
            runner = runner->next;
            count++;
        }
        if(count - n == 0){
           return head->next;
        }
        for(int i=0;i<count-n;i++){
            if(i==count-n-1){
                current->next = current->next->next;
                return head;
            }
            else{
                current = current->next;
            }
        }
        return head;
    }

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *