[c++]Why can't I code in this logic?


  • 0
    S

    Hello guys,

    Here is the code:

    void Solution::deleteNode ( ListNode* node )
    {
        node = node->next;
    }
    

    Why can't I assign the node as a whole? I mean, isn't the code above equivalent to:

    void Solution::deleteNode ( ListNode* node )
    {
        node->val = node->next->val;
        node->next = node->next->next;
    }
    

    When I was coding binary tree problems, it seems legit to assign every properties of a leaf by just doing:

    void Example::invertLeaves ( Leaf* root )
    {
        Leaf* _temp = root->left;
        root->left = root->right;
        root->right = _temp;
    }
    

    Both value and children relationships are properly assigned. Maybe I am missing something stupid but right now I can't get out of my circle.

    Thanks!


  • -1
    S
    This post is deleted!

  • 1
    C

    The first code isn't equivalent to the second one.

    The first code only move the pointer "node" to the next node.

    The second code modifies the value in the node which is point by the pointer "node". It is equivalent to:

    void Solution::deleteNode ( ListNode* node )
    {
        *node = *node->next;
    }

  • 0
    Q
    void Solution::deleteNode ( ListNode* node )
    {
        node = node->next;
    }
    

    this answer may chang the head and the list will not access,that means you delete the whole list.

    void Solution::deleteNode ( ListNode* node )
    {
        if(node->next){
           node->val = node->next->val;
           node->next = node->next->next;
        }
        else
           node = NULL;
    }
    

    this answer will delete the next pointer and the next will not be head.


Log in to reply
 

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