C++ standard solution

  • 1
    class Solution {
    void deleteNode(ListNode* node) {
        if (node==NULL) return;
        ListNode *temp = node->next;
        node->val = temp->val;
        node->next = temp->next;
        delete temp;

  • 0

    Why use delete, I think temp is a local variable.

  • 0

    I am not just deleting the pointer temp, I am deleting the node data that temp points to. Temp is just a pointer, it will be destructed automatically. But the node data won't.

  • 0

    if it's the last node, then node->next==NULL, should we delete the node instead of temp?

  • 0

    it is impossible to delete the last node, because we don't know the previous node. So the problem says "Write a function to delete a node (except the tail) in a singly linked list". except the tail..

Log in to reply

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