-1

In the code there is Node next in class Node. I am not able to understand what exactly it is doing. Is it creating a object named next. And is there value getting stored in it when nodeA.next = nodeB is used. I am trying to learn LinkedList but i am not able to get what is exactly happening.

  class Node{
     int data ;
     Node next;
     Node(int data){
        this.data = data ;
     }
  }

  Node nodeA = new Node(6);
  Node nodeB = new Node(3);
  Node nodeC = new Node(2);


 nodeA.next = nodeB;
 nodeB.next = nodeC;
Mercury1337
  • 333
  • 4
  • 13

1 Answers1

6

Lets split the code up and explain the parts:

class Node {
}

This is the syntax to create a new class. The class is named "Node".

int data;

This defines an instance variable. Each instance of type Node should have a variable called data of type int.

Node next;

This defines another instance variable. It is called next and it holds a reference to a Node.

 Node(int data){
    this.data = data ;
 }

This is a so called constructor. It takes an argument data and then it is stored inside the instance variable data. (The instance variable is referenced with "this.", because the parameter data is hiding the instance variable with the same name.)

That was the class itself. So now we look at the use of it (This does not make sense outside a class / function. Such code should be part of a function e.g. inside a main function):

Node nodeA = new Node(6);
Node nodeB = new Node(3);
Node nodeC = new Node(2);

This creates 3 instances of the class node and it is storing it inside nodeA, nodeB and nodeC variables.

nodeA.next = nodeB;
nodeB.next = nodeC;

Here, we set the next instance variable of nodeA and nodeB and assign the nodeB and nodeC.

And this gives us a so called linked list. An element of the list can point to another element (or when there is no element reference in it, then it is null by default.

Did this help understanding the code? If not: Where exactly do you have problems understanding the code?

Konrad Neitzel
  • 736
  • 3
  • 7