Accepted C codes but does not looking making sense to delete the last node


  • 1
    L
    void deleteNode(struct ListNode* node) {
        struct ListNode *p = NULL;
        if (!node) return;
        p = node->next;
        if (!p) return;
        node->val = p->val;
        node->next = p->next;
        free(p);
        return;
    }
    

    This is my solution and it is accepted in 4ms. However, I am not doing anything when the node to delete is the last one. If this is accepted, caller needs to take measurement avoiding dereferencing the last one. That way, we are not "deleting" or "avoiding" the last node.


  • 0

    Don't worry, the problem statement explicitly excludes that case:

    "Write a function to delete a node (except the tail) in a singly linked list"


  • 0
    L

    Good point. Did not read very carefully :)


  • 0
    D

    Hi Lohzhang,
    I don't quite get it..
    p points to the node after "to-be-delete" node. Why would you want to free it ?
    Shouldn't we free(node) instead ?
    Thanks


  • 0
    L

    node is the one to delete but attributes in node are replaces by attributes in p. Therefore, node replaces p and its next pointer points to p'next. This node is part of the list but p is not accessible from list. So we should free p instead of node.


Log in to reply
 

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