My Different Approach.. C++


  • 1
    E

    Looks like most solutions are about fast-slow runner differed by n.
    Here I am using quite different approach; not sure this can be seen as one pass though.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    
    class Solution {
    public:
        int remove(ListNode* head, const int& n)
        {
            if (!head)
                return 0;
                
            int value = remove(head->next, n);
            if (value == n)
            {
                head->next = head->next->next;
            }
            
            return value + 1;
        }
    
        ListNode* removeNthFromEnd(ListNode* head, int n) 
        {
            if (remove(head, n)==n)
                return head->next;
                
            return head;
        }
    };

Log in to reply
 

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