Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do we have to create tmpNext in this java method?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading