Reputation: 1
I'm, learning how linked list works but i can't understand some simple stuff like how Node.next work, i think the problem is that i don't understand how reference in java works.
public class Node {
int date;
Node next; //This line i don't understand, what are we doing when we declare class type inside the same class
}
but there is also:
public class SinglyLinkedList {
private Node first; //What is the difference between this line and the line in the class Node?
Upvotes: 0
Views: 547
Reputation: 270
you creating an object(in this case Node)and that is important for you what is next object (or previous or parent or child ,etc) to point that object you need a variable with type of same object.
Upvotes: 0
Reputation: 140573
Node next;
Is what you could call a forward reference. It tells you that an instance of that class Node
has a reference that can point to another Node instance.
Initially of course, that reference will be null (not pointing to another Node
). But when you start building your list of nodes, that works by one Node ... linking to the next
Node, by changing that field value from null, to point to some instance of that class. That is how simple linked lists work: you start with a single root node, and adding notes to the list means: updating such next
fields.
From that point of view, there is no "real" difference between the two classes above. You could as well go:
Node firstNode = new Node(5);
Node secondNode = new Node(42);
firstNode.next = secondNode;
The main point of having a distinct class with a first
field is for conceptual reasons: that second class "tells" the reader: "my purpose is to contain the first Node object of a list".
You can turn here for more extensive explanations about classes, objects, and references.
And note: the really crucial point here is that, by default, when you do a new Node()
call, that field next
starts of with null
.
Upvotes: 1