My C++ solution in 1 line


  • 19
    M
    class Solution {
    public:
        void deleteNode(ListNode* node) {
            *node = *(node->next);
        }
    };
    

    if the node should be freed, we need 3 lines:

    class Solution {
    public:
        void deleteNode(ListNode* node) {
            ListNode* temp = node->next;
            *node = *temp;
            delete temp;
        }
    };

  • 0
    E

    the question is Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Delete the node by the pointer.


  • 2
    M

    Why did this fail?

    class Solution { 
    public:
        void deleteNode(ListNode* node) {
            node = node->next;
        } 
    };

  • 0
    P

    Because you're modifying the pointer but not the real data, and the pointer is just a copy of the real address.


  • 4

    @phu1ku @moto

    The tricky point is that we can not use

        node=node->next
    

    Because we have not change the address content stored in the previous node.

    In fact , a linked list will be stored like this:

    head ->  {val1,   address2}    {val2, address3}  {val3, address4}   {val4, NULL}
    

    So, if we are given access to the *cur = {val3, address4}

    If we want to delete the *cur, we have to change the content stored in *cur.

    If we use cur=cur->next, what happens ?

    OOPS ! nothing happens ... because the "address#" stored in the linked list keeps no changing!

    So "cur=cur->next" makes no impact on the linked list.


Log in to reply
 

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