My c++ Solution


  • 0
    class Solution {
    public:
               ListNode* removeNthFromEnd(ListNode* head, int n) {
            if(head==NULL) return head;
            if(head->next==NULL) return 0;
            
            int i;
            ListNode *p=head,*fakeNode=new ListNode(-1), *t=0;
            fakeNode->next=head;
            
            //traverse
            for( i=0; p->next &&(p=p->next);){
                ++i;
                if(i>=n) fakeNode=fakeNode->next;  
            } 
            t=fakeNode->next;
            fakeNode->next=fakeNode->next->next;
            delete t;
            
            return i<n?fakeNode->next:head;
        }
    };

Log in to reply
 

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