C++ using pointer of pointer


  • 0
    L

    Handle the special case where the head needs to be removed by pointer of pointer, instead of constructing of a "Head Node".

    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode** pp = &head;
            ListNode* p = head;
            for(;n>1;--n){
                p = p->next;
            }
            while(p->next){
                pp = &(*pp)->next;
                p = p->next;
            }
            // save and free *pp
            *pp = (*pp)->next;
            return head;
        }
    };
    

Log in to reply
 

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