Why *node=*node->next;works but *node=node->next; does not?


  • 0
    Y

    Can someone plz tell me why *node=*node->next;works but *node=node->next; does not?


  • 5
    R

    Look at here: C++ operator precedence

    The memory access operator "->" has higher precedence than the dereference operator "*". As a result, the code

    *node = *node->next;
    

    is essentially the same as

    *node = *(node->next);
    

    In this problem, node and node->next are both pointers to ListNode. Therefore, *node and *(node->next) are both ListNode object, and *node=*(node->next); is doing copy assignment operation: The content that is pointed by (node->next) is copied into the content that is pointed by node.

    However, if you do *node = node->next, there is a type mismatch problem here, because *node has type of ListNode while node->next is ListNode *. This line of code is trying to copy the value of a pointer to an instance of the structure, which is invalid.


  • 0
    Y

    Thx a lot for the help!


Log in to reply
 

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