I am kind new to Java. Can anyone answer my question ? Thanks!
node = node.next;
Why this doesn't work?
You're just advancing node, which you can think of as a pointer along a list.
To actually drop off a node you need to modify the reference of the previous node to point to the next node, since the question asks that you remove the given node.
Since we don't have access the previous node, the next best thing we can do is to 'copy' over the values of the next node, and then point to the node after the next node.
This way we 'fold over' the list by dropping off the current value, replacing it with the next value, so it looks like we 'deleted' a node.
node.val = node.next.val; //copy the next node's value over to replace the current nodes value node.next = node.next.next; //modify the next value to point to the node after the next.
If we don't modify the reference
node.next the list will now have 2 nodes with the same value.
@shinyoo because the previous node (let's say
previous) will still point to the current node (
node), think of it as you want to forget a location, and you do that with node.next. But the previous node still remembers it, so you need to make sure the previous node also forgets it and no one will ever point to this node you want to forget ever again.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.