• + 7 comments

    Magic C++ solution

    Elegant as the recursive one - just 3 lines of code

    Only faster, less memory footprint and way cooler!

    It essentially just finds the address of the node that's to be deleted and places the next node's address there.

    (Actually just replaces the pointer values, using pointers to pointers..)

    Code:

    SinglyLinkedListNode* deleteNode(SinglyLinkedListNode* head, int n) {
        auto x=&head;
        for(int i=0;i<n;i++,x=&(*x)->next); *x=(*x)->next;
        return head;
    }