Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Ene Catalin
Ene Catalin
1,931 Points

How/When does the "next" variable get initialized with the adress of the next element? (LinkedLists)(see picture)

The insert method adds an element at the end of the list.

Imgur

Ene Catalin
Ene Catalin
1,931 Points

This is from a tutorial video I found on youtube. The Treehouse videos on LinkedList are explained using Python and I don't understand the syntax.

1 Answer

The last node points at null for the LinkedList implementation, so I think it's okay. When there is only one node, that node is a head and also the last node, so it points at null. When you insert the 2nd data, then because head node exists, the program goes to else clause where the head node that is also the last node points at null, so the program doesn't even go into the while loop (head.next is null, which is defined in Node class). And then this node gets this head node get next initialized. For the second thought, it will be better to understand if Node class explicitly initializes Node point to null:

public class Node {
  int data;
  Node next = null;
}

Is this from any treehouse exercise? Where does this come from?