The method inserts a new Node object after the current one. I don’t understand why we do not simply have in the method this.nextNodeRef = nodeLoc; all alone. Why is it import to conserve the original reference to the Node in a temporary variable? Why do we store it after the current Node nodeLoc in the nextNodeRef variable (another IntNode)?
public void insertAfter(IntNode nodeLoc) {
IntNode tmpNext;
tmpNext = this.nextNodeRef;
this.nextNodeRef = nodeLoc;
nodeLoc.nextNodeRef = tmpNext;
}
>Solution :
The idea is that any given IntNode object ‘knows’ what the next item in the list is.
Originally, you have, say:
A[5] -> B
B[8] -> C
C[12] -> D
D[2] -> E
(i.e., the first node is called ‘A’, has value 5, and knows that the next node is B. The B object has value 8, and knows that the next node is C, and so on).
Now you want to insert Z after B. The IntNode object representing Z has a blank nextNodeRef.
To do this, you want B to no longer point at C, but to point at Z.
However, if that’s all you do, the list is now A, B, Z and it ends there. If you want A, B, Z, C, D, E, then Z‘s nextNodeRef needs to be pointing at C.
Where do you get C from?
Well, that used to be what B was pointing at.
That’s what the code does: "Saves" C, updates B to point at Z, then updates Z to point at the thing you saved, which is C. Then, you get:
A -> B -> Z -> C -> D -> E