Accepted C++ solution with explanation in comments


  • 0
    H
    class Solution {
     public:
       void deleteNode(ListNode* node) {
          ListNode* nextNode = node->next; // get next node.
          node->val = node->next->val; // current node becomes next node.
          node->next = nextNode->next; // the actual next node becomes garbage, so we skip it.
        } 
    };

  • 0
    C

    It seems that in you code you do not "delete" a node.


  • 0
    B

    I feel confused about why node->val=node->next->val?
    I think node->next->value should be deleted,and node->val=nextNode->next->val.


  • 0
    H

    The question asks you to delete the input node. Since I don't have the access to the previous node, the only thing I can do is mutate the input node into the next node, and let it point to the one after next one. As a result, the input node disappears. You can use an example to verify my code.


  • 0
    S

    sorry when the node is the last node of the list; your code make nothing.


Log in to reply
 

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