C++ 3ms A different solution


  • 0
    D
    ListNode* removeNthFromEnd(ListNode* head, int n) {
            if(!head)return head;
            if(!(head->next))return head->next;
            if(!(head->next->next)){
                if(n==1)head->next->val=head->val;
                if(n==2)return head->next;
            }
            int len=0;
            ListNode* cur=head;
            while(cur){
                len++;
                cur=cur->next;
            }
            if(n==len)return head->next;
            cur=head;
            while(len-n-1){
                cur=cur->next;
                len--;
            }
            if(cur->next)cur->next=cur->next->next;
            return head;
        }
    

Log in to reply
 

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