Why "node = node.next" doesn't work?


  • 2
    L

    This might sound so dumb, but wouldn't node=node.next work?


  • 3
    Q

    Is it in Python?
    Then you just let the name "node" refer to node.next.
    But the variable initially pointed by "node" is still in the list and never change.


  • 0
    E

    Why it doesn't work in JAVA? Still quite don't understand why node= node.next doesn't get a copy of the next node to the current node.


  • 0
    E

    Single linked list: 1->2. If node refers left node with value 1 then node.next refers right node. If you state 'node=node.next;', then now reference with a name 'node' would point to the right node with value 2, nothing changes. Thinking it as a address assignment, not a value assignment or creating something new.


  • 0
    J
    This post is deleted!

  • 0
    R

    because it is as a parameter passed to the function, so it is a copy of the original node, you should change its content, but not its address.


  • 1
    C

    public class test {

    public static void main(String[] args) {
    	ListNode n1 = new ListNode(1);
    	ListNode n2 = new ListNode(2);
    	n1.next = n2;
    	
    	Solution s = new Solution();
    	s.deleteNode(n1);
    	System.out.println(n1.val);
    	System.out.println(n2.val);
    
    	n1 = n1.next;
    	System.out.println(n1.val);
    	System.out.println(n2.val);
    }
    

    }

    public class Solution {
    public void deleteNode(ListNode node) {
    node = node.next;
    }
    }

    this test outputs:1222

    so this question ask you write a function to delete a node of a linkedlist, that means the variable of "node" is a copy of reference, "node" points to contents of "n1". When you use "node = node.next;", you change reference of "node" which would point to contents of "n2", but you don't change contents of the reference that you pass to the function, it is "n1" in this case;

    but "node = node.next;" would work outside the function, it is "n1 = n1.next;" in this case;


Log in to reply
 

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