Share my one pass c++ code


  • -1
    W
    ListNode *removeNthFromEnd(ListNode *head, int n) {
            int cur = 0;  // keep current position
            ListNode* p = head;
            ListNode* np = head;
            while(p != NULL) {
                p = p -> next;
                cur++;
                if(cur > n + 1) //begin to move if current position is large enough to count n numbers
                    np = np -> next;
            }
            if(cur <= n)
                return head -> next;
            p = np -> next;
            np -> next = p -> next;
            return head;
        }

Log in to reply
 

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