68838
![How to link a node with a next node in Java [closed]](https://www.xszz.org/skin/wt/rpic/t4.jpg)
Question:
I will begin by creating the head node:
Node head = new Node();
To link head node to the next node. I will assign to the field of type Node in node object
The zero is to represent the number of the node. This node is number zero.
Node node = new Node(0,head);
public class Node {
private Object data;
private Node next;
public Node()
{
data = null;
next = null;
}
public Node(Object x)
{
data = x;
next = null;
}
public Node(Object x, Node nextNode)
{
data = x;
next = nextNode;
}
}
Is this the proper way to link nodes together?
Answer1:The way I normally see is using a LinkedList.
public class Node {
public Object data;
public Node next = null;
Node(data) {
this.data = data;
}
}
class LinkedList{
public Node head = null;
public Node end = null;
void insert(Object data) {
if(head == null) {
head = new Node(data);
end = head;
} else {
end.next = new Node(data);
end = end.next;
}
}
}
This is used as follows:
LinkedList= new LinkedList();
list.insert(2);
list.insert(3);
list.head;
Answer2:In Java you refer to all objects via references (i.e., pointers). The only time you deal with actual values is with primitive types.
So doing next = nextNode
causes next
to point to the same location that nextNode
points to.
<strong>TL;DR;</strong> Yes. :)