I am calling a constructor in a method to insert new nodes.While I am adding new node default constructor is creating new node with default values . I want to just insert values using insert method as in below code . Is there any way I may avoid first node being default.
class Node {
Node right, left;
int data = 0;
Node() {
}
Node(int data) {
this.data = data;
}
public void insert(int value) {
if (value <= data) {
if (left == null) {
left = new Node(value);
} else {
left.insert(value);
}
} else {
if (right == null) {
right = new Node(value);
} else {
right.insert(value);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node new_node=new Node();//creating first node with 0 value
new_node.insert(5);
new_node.insert(4);
new_node.insert(9);
new_node.insert(23);
new_node.insert(70);
new_node.display();
}
}
You could use the first value as the first element:
Node new_node = new Node(5); // create 1st node with 1st value
Or you could define a new default constructor with a value that you don't expect to be in the list (let's say -1
), but you'd have to be careful about this element in your list that is not really part of the list, and that makes implementing other operations trickier:
Node() { data = -1; }
But all this is symptom of a bigger problem: you shouldn't handle the head of your list in the Node
class. It'd be better to create a new class, let's call it MyList
and define a Node head
attribute on it, and all insert/update/delete/search operations should be implemented on that class.
It's important to keep the head separate, because there will be operations that modify the head
. For example, your insert()
method doesn't consider the case when the node to insert should go at the beginning of the existing list.