My simple solution with C++


  • 3
    Z
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* a=head;
        ListNode* current=head;
        
        for(int i=0;i<n;i++)
        {
            current=current->next;
        }
        
        if(!current)
        {
            head = head->next;
            return head;
        }
        
        ListNode* b=current;  //create a new listnode to touch the end of the list "head", n node earlier than "a".
        
        while(b->next)
        {
            a=a->next;
            b=b->next;
        }    
        a->next=a->next->next;
        
        return head;
    }

  • 0
    S

    不对啊 当链表为 1 2 3 4 n=3 是 不能删除第二个节点啊


  • 0
    Z

    我试过了,没有问题的,你重新试试


Log in to reply
 

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