A C++ solution


  • 0
    W
    class Solution 
    {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int j) 
        {
            int count=0;
            ListNode *n=head;
            for(; n; n=n->next,++count)
                ;
            
            n=head;
            int i=count-j-1;
            if(i < 0)
                return head->next;
            
            //cout << "i:" << i << '\n';
            while(i-->0)
                n=n->next;
            
            n->next=n->next->next;
            return head;
        }
    };
    

Log in to reply
 

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