This is my Accepted code


  • 0
    M
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if (NULL == head)
            return NULL;
            
        ListNode *pCurNode = head;
        for (int i = 1; i < n; i ++) {
            if (pCurNode->next) {
                pCurNode = pCurNode->next;
            }
            else {
                return NULL;
            }
        }
        
        // find the nTh of the end
        ListNode *pNBehinde = head;
        while(pCurNode->next) {
            pCurNode  = pCurNode->next;
            pNBehinde = pNBehinde->next;
        }
        
        //cout << pNBehinde->val << endl;
        
        // delete the nTh of the end
        if (pNBehinde == head) { // head node
            head = head->next;
            delete pNBehinde;
            pNBehinde = NULL; 
        }
        else if (NULL != pNBehinde->next) { // not head or tail
            ListNode *pNext = pNBehinde->next;
            pNBehinde->val = pNext->val;
            pNBehinde->next = pNext->next;
            delete pNext;
            pNext = NULL;
        }
        else { // tail
            ListNode *pNode = head;
            while(pNode->next != pNBehinde) {
                pNode = pNode->next;
            }
            pNode->next = NULL;
            
            delete pNBehinde;
            pNBehinde = NULL;
        }
        
        return head;
    }

Log in to reply
 

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