Share my AC c++ code, 10ms


  • 0
    S
    class Solution {
    private:
        int helper(ListNode *node){
            if(!node->next) return 1;
            else return (helper(node->next)+1);
        }
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            ListNode *p;
            p = head;
            
            if(helper(p)==n){
                head = head->next;
                return head;
            }else if(helper(p)<n) return head;
            else{
                while(helper(p)!=n+1){
                    p = p->next;
                }
                //remove the next node of the current node
                p->next = p->next->next;
                return head;
            }
            
        }
    };

  • 0
    R

    It's not an one pass solution, dude.


Log in to reply
 

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