Sharing my solution


  • 0
    L
    class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            
            if(head == NULL)
            return head;
            
            ListNode *c,*p;
            
            c = head;
            p = NULL;
            
            int count = 0;
            
          
    
    
                while(c !=NULL )
                {
                    c = c->next;
                    count++;
                }
                
                c = head;
                
                for(int i = 0;i < count - n ; i++)
                {
                    if (c == NULL)
                    return head;
    
                    p = c;
                    c = c->next;
                }
                
                if(p == NULL)
                {
                    head = c->next;
                }
                else
                {
                    p->next = c->next;
                }
                
                delete c;
                
            
           
    
            return head;
            
        }
    };
    

    I believe this is a pretty good solution. Does anyone have any tips on improving it if possible?


Log in to reply
 

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