We are trying to write a method to delete a node with a particular key from a linked list implementation of a LUT.
Summary of the code I wrote:
public void delete (String k) {
Node currNode = listHead;
Node prevNode = listHead;
Key key = new Key (k);
while (!currNode.key.equals(k) && currNode != null){
prevNode = currNode;
currNode = currNode.next;
}
if (currNode == listHead) {
listHead = listHead.next;
} else {
prevNode.next = currNode.next;
}
}
My friend wrote essentially the same thing but didn't use a previous node pointer, and instead wrote as his last line:
currNode = currNode.next //detach point, override
Are both of these equivalent? I think what I'm confused about it Java memory management.
If you have already created your listHead
Node somewhere else, and you write:
Node currNode = listHead;
currNode
is only storing a reference to the memory location where listHead
is stored, right? So in the while-loop when you do currNode = currNode.next
, what you're doing is going to the memory location referenced in currNode
and looking at the variable next and storing the reference to that memory location in currNode
? So basically updating where currNode
is pointing to. This would mean that my friend's code was wrong , right? Since his code would similarly mean: "update the reference currently in currNode
with the memory location of currNode.next
".
Would someone mind helping me remove the fog please?
You friend's can't be right because one has to change the .next
field of a Node
to delete a Node
from the list.
As I imagine you know, to delete node N
from a list you need set the .next
field of node N-1
to refer to node N+1
. Your friend's approach can't possibly be doing that because it's not changing any node's .next
field.
As for memory, once N-1
's .next
field refers to N+1
, then N
is no longer being kept alive by the list. Whether or not it is eligible for garbage collection depends on if anything else in the program has a reference to it. But the list has now washed its hands of it.