Why setting the tail to null is wrong?


  • 0
    T

    here is my Java code,
    I set the last node to null, but does not get accepted.

    public void deleteNode(ListNode node) {

        if(node == null)
           return;
           
        while(node.next != null){
            node.val = node.next.val;
            node = node.next;
        }
        
        node = null;
        
    }

  • 0
    L

    I think, java use call by reference by default. The "node" is just a pointer to the last node, set node to null does not affect the actually memory.
    what you need to do here is to set the last but one node's next pointer to null.
    I get used to C++, so get used to use term "pointer".
    In fact, you do not need to scan all the remain list.
    You may consider the following solution:

     public void deleteNode(ListNode node) {
       if(node == null)
            return;
        node.val = node.next.val;
        node.next = node.next.next;
    

    }


  • 0
    T

    Thanks. I have a misunderstanding about null.
    node.next = node.next.next ?
    what if the node is the tail, nose.next.next should be illegal.


  • 0
    L

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


Log in to reply
 

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