I don't know what's wrong with my answear? I traverse twice to do the delete


  • 0
    Z
      ListNode* top=head;
        ListNode* traverse=head;
        int number=0;
        while(head!=NULL)
        {
            head=head->next;
            number++;
            
        }
        int traverse_number=number-n-1;
        for(int i=0;i<traverse_number;i++)
        {
            traverse=traverse->next;
            
        }
    
        ListNode* next=traverse->next;
        traverse->next=next->next;
        delete next;
        return top;
    }

  • 0
    S
    //Your code is not considering all the corner cases 
    
    //like for example 
    //4->5->6 ; delete 3rd element from last which is node with value 4(head).
    
    //For this case your code will delete node with value 5 instead of node with value 4 since
    //traverse_number is negative(2-3-1=-2). 
    
    //Therefore traverse==head and then deletes traverse.next.
    
    //So for this case your code will return 4->6 instead of 5->6.
    
    //Following modification to your code will work
    
    ListNode* top=head;
            ListNode* traverse=head;
            int number=0;
            while(head!=NULL)
            {
                head=head->next;
                number++;
            }
            //******************************
            if(number==n){
                top = traverse->next;
                return top;
            }
            //*******************************
            int traverse_number=number-n-1;
            for(int i=0;i<traverse_number;i++)
            {
                traverse=traverse->next;
    
            }
    
            ListNode* next=traverse->next;
            traverse->next=next->next;
            delete next;
            return top;

Log in to reply
 

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