4ms C solution (with explanation)


  • 12
    A

    /* Here's my simple 4ms solution
    We have been given a pointer to the node to be deleted.
    We know that while deleting a node from the linked list, we have to fix the links between the previous and the next node. The following are the steps to achieve this:

    1. Find out the next node of the pointer to the node that we have.
    2. Copy the data from the next node to the node to be deleted.
    3. Fix the link and delete the next node

    */

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

  • 0
    G

    My code is the same but runs 16ms.


Log in to reply
 

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