RealFL
RealFL

Reputation: 117

How to properly update linked list

Let's say I have two classes, object1 and object2. I want to add a object1 instance to the end of a linked list in an instance of object2 (that is, the method to add object1 to the linked list is in the object2 class). Supposing the linked list already has one object, why would the following not update my linked list:

object1 a = firstObject1;
while(a != null) {
    a = a.next;
}
a = b;

where b is the object with which the adding method is called. To be clear, the issue I'm getting is that when I print the id of every object in the linked list, I don't see the new object.

Note: This is in fact homework, so I can't use helper methods or import libraries.

Upvotes: 1

Views: 1175

Answers (2)

luk2302
luk2302

Reputation: 57114

You need to set a.next to b for the last a. a = b does basically do nothing since a is a local variable.

object1 a = firstObject1;
while(a.next != null) { // find the last a, the one which does not has a next
    a = a.next;
}
a.next = b; // set the next of the last a

Additionally please start giving your classes more meaningful names, dont put numbers in them and let them start with an uppercase letter.

Upvotes: 2

Jacob G.
Jacob G.

Reputation: 29680

The issue here is that setting your local variable a to your new node b will go out of scope at the end of this block, resulting in no new node being added. The correct way to do this would be to check when a.next is null so you can set a.next to b:

object1 a = firstObject1;

while (a.next != null) {
    a = a.next;
}

a.next = b;

Upvotes: 3

Related Questions