Thought is to use 2 pointers with different steps, about 1 loop


  • 0
    D
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode *n1;
            ListNode *n2;
            int n1Cnt,n2Cnt;
            n1Cnt=1;
            n2Cnt=1;
            n1=head;
            n2=head;
            
            if(head==NULL)
                return head;
                
            while(1)
                {
                    if(n1->next==NULL)
                        break;
                    else
                        {
                        n1Cnt++;
                        n1=n1->next;
                        }
                    
                    if(n2->next==NULL) /* n2 step forward 1 */
                        break;
                    else 
                        {
                        n2Cnt++;
                        n2=n2->next;
                        }
        
                    if(n2->next==NULL) /* n2 step forward 2 */
                        break;
                    else 
                        {
                        n2Cnt++;
                        n2=n2->next;
                        }
                        
                    if(n2->next==NULL) /* n2 step forward 3 */
                        break;
                    else 
                        {
                        n2Cnt++;
                        n2=n2->next;
                        }
                }
                
            if(n2Cnt-n1Cnt-n>=0)
                {
                for(int i=1;i<=n2Cnt-n1Cnt-n;i++)
                    n1=n1->next;
                if(n1->next!=NULL)
                    n1->next=n1->next->next;
                }
            else if(n2Cnt>=n)
                {
                    n1=head;
                    if((n2Cnt-n)==0)
                        {
                        n1=n1->next;
                        return n1;
                        }
                        
                    for(int i=1;i<n2Cnt-n;i++)
                        n1=n1->next;
                        
                    if(n1->next!=NULL)
                        n1->next=n1->next->next;
                }
                
            return head;
        
            }
        };

Log in to reply
 

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