I'm working on a java project that adds nodes to the end of a linked list with int values . However the nodes values must range between 0....n-1 inside the linked list . I have already written code on how to append an element at the end of the list and check if an element already exists . The problem is how to add elements incrementally and start from 0 .
ex.{} add 3 : error (you must add 0)
{0} add 2 : error (you must add 1)
I have written code bellow :
class ItemNode {
public int item;
public ItemNode next;
public ItemNode(int item) {
this.item = item;
this.next = null;
}
}
class ItemsList {
private int nbNodes;
private ItemNode first;
private ItemNode last;
public ItemsList() {
this.first = null;
this.last = null;
this.nbNodes = 0;
}
public int size() {
return nbNodes;
}
public boolean empty() {
return first == null;
}
public int append(int item) {
ItemNode node = new ItemNode(item);
if(this.empty())
{
first=node;
last=node;
nbNodes++;
}
else if (member(this.first,node.item))
{
System.out.println("Node already exists ");
}
else
{
last.next=node;
last=node;
nbNodes++;
}
return nbNodes;
}
simply nbNodes
will act as "whose turn is this"
for example, if the list is empty, then nbNodes equals zero, means the element that should come next is zero, if the nbNodes equals five, then the next element should be five and so on.
so the process is to check in the append method if the coming number equals nbNodes
or not and act based on that.
you may consider changing it's name to suite it's responsibility now, or add a new one for this task.