4ms C code, 2 lines


  • -3
    M

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


  • 4
    J

    Don't forget to free the node that you deleted.


  • 5
    L

    If you don't care about freeing, there's a one-line solution:

    *node = *(node->next);
    

    To free this one you need to do this:

    struct ListNode* tofree = node->next;
    *node = *(node->next);
    free(tofree);

  • 0
    D

    Hi lee17,
    I don't quite get it..
    tofree points to the node after "to-be-delete" node. Why would you want to free it ?


  • 0
    R

    The content of the "tofree" is copied to "node" , so "tofree" can be freed. The point is we need to remove the node containing a specific val, not the node pointed by "node"


Log in to reply
 

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