My 17 line C++ code


  • 0
    B
    ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode** arr = new ListNode*[n + 1];
            ListNode *p = head;
            int index = 0;
            int full = 0;
            while(p)
            {
                index = index % (n+1);
                arr[index++] = p;
                p = p->next;
                if(index == n+1) full = 1;
            }
            if(!full) return head->next;    //if not full, meaning head node is to be deleted
            arr[index % (n+1)]->next = arr[(index+1)%(n+1)]->next;
            delete []arr;
            return head;
        }
    

Log in to reply
 

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