Why a linked list needs a start object when we initially already have "next" in the Node class?
Solution 1:
If you mean why you need to create a new Node to add the next object and why you can't just give a value to the next object like start.next = 5
, it's because the .next
object is of type Node which doesn't match the integer type of 5.
What you can do, is to create a .next()
function for the Node class.
this could be done like below:
class Node {
private int data;
private Node next; // reference object
//Constructor
public Node(int data) {
this.data = data;
public next(int value) {
this.node = new Node(value);
}
}
and now you can do this to add the next value to your linked list:
public static void main(String[] args) {
Node start = new Node(22);
start.next(32);
}