I'm working on a project that appends nodes to the end of a linked list. However, I cannot add the same node twice inside a list and when I append the same node as before the nodes increase naturally and I don't get a message saying the node already exists. Here's the code
public int append(int item) {
ItemNode node = new ItemNode(item);
if (this.empty()) {
first = node;
last = node;
nbNodes++;
} else if (node == findNode(item)) {
System.out.println("Node already exists");
} else {
last.next = node;
last = node;
nbNodes++;
}
return nbNodes;
}
private ItemNode findNode(int key) {
if (this.empty()) {
return null;
} else {
ItemNode current = this.first;
while (current.item != key) {
if (current.next == null) {
return null;
} else {
current = current.next;
}
}
return current;
}
}