[recommend for beginners]clean C++ implementation with detailed explaination


  • -1

    We just cover the value of the given node and set its value to the next value and its next pointer to the next pointer .

    Just the same as the way : *node = *(node->next);

    class Solution {
    public:
        void deleteNode(ListNode* node) {
            if(!node->next)  {
                node=NULL;
                return;
            }
            node->val = node->next->val;
            node->next = node->next->next;
            
            /* *node = *node->next */
        }
    };

  • 0
    Q

    1->2->3->4. remove 3.

    After pointing 2->4, 3 will be a "leak".

    you need to create a temp pointer to node->next before setting and delete temp later.


  • 0

    Thanks for your advice


  • 0

    The tricky point is that we can not use

        node=node->next
    

    Because we have not change the address content stored in the previous node.

    In fact , a linked list will be stored like this:

    head ->  {val1,   address2}    {val2, address3}  {val3, address4}   {val4, NULL}
    

    So, if we are given access to the *cur = {val3, address4}

    If we want to delete the *cur, we have to change the content stored in *cur.

    If we use cur=cur->next, what happens ?

    OOPS ! nothing happens ... because the "address#" stored in the linked list keeps no changing!


Log in to reply
 

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