0

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? 
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • What *do* you understand about object references in Java? It's kinda hard to fill in the blanks if you don't tell us where they are ... – meriton Sep 14 '19 at 13:08
  • (is this about Java syntax or the concept of object references in general?) – meriton Sep 14 '19 at 13:32

2 Answers2

1
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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

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.

kankan256
  • 210
  • 1
  • 4
  • 18