My Single Loop C++ Solution


  • 0
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode* dummy = new ListNode(0);
            dummy->next = head;
            ListNode* fast = dummy;     // to find the last node
            ListNode* slow = dummy;     // to find the (n+1)th node from end of list
            while (fast != NULL) {
                fast = fast->next;
                if (n >= 0) {
                    --n;                // 'slow' is nth nodes behind 'fast'
                } else {
                    slow = slow->next;
                }
            }
            slow->next = (slow->next)->next;    // remove the node
            return dummy->next;
        }
    };
    

Log in to reply
 

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