When we delete a node in java, we simply do
n.data=n.next.data;
n.next=n.next.next;
(To delete the node n.next).
Does this complete the purpose of deletion or we have some method to remove the deleted node (like free(n.next) in C)?
When we delete a node in java, we simply do
n.data=n.next.data;
n.next=n.next.next;
(To delete the node n.next).
Does this complete the purpose of deletion or we have some method to remove the deleted node (like free(n.next) in C)?
You cannot delete an object in Java, per se. You may only mark an object eligible for garbage collection by removing all references to its instance. The actual time that garbage collection will run and the memory will be freed is determined by the JVM and cannot be explicitly controlled. In your example, if you remove the only reference to some Node, only then will it becomes eligible for GC.
In java, there is no need of deleting java objects explicitly. The JVM automatically deletes java objects using garbage collector when there are no more references to the object. So if You don't use an object furthermore just null the reference of it.
So, Your Code
n.data=n.next.data;
n.next=n.next.next;
implicitly removes (there is no way of accessing the previous n.next Object) the reference of the unnecessary object.
You need to make sure that there are no references hanging around to the "deleted" node. May be a little clarification to Kon's answer - you cannot remove an object, and when all references to it go out of scope, this object will be (eventually) garbage collected by the JVM. Otherwise, if you expect some reference to stick around, you should help the JVM by programmatically assigning it to null, or, alternatively, as in your code below, reassign that reference to another object.
n.next=n.next.next
So your code is fine, if you know that n.next in the first line of your code is the only reference to the node to be deleted, or all other references are variables local to the method, and will go out of scope when the method returns.
You can simply say:
n.next = n.next.next
In java this is sufficient.
nodeToDelete is pointless and miss leading.