Search code examples
javalistfindnodes

Java : check if node exists in linked list


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;
    }
}

Solution

  • As Eran already mentioned, you should use equals by overriding it as per your needs. The reason you are not getting the message is that you are comparing the references of newly created object.

    ItemNode node = new ItemNode(item); 
    

    with that of an existing one i.e

    node == findNode(item).// Here findNode will return an existing node, so they are not pointing to same object
    

    Possible Solutions :

    1) You can make your findNode(int key) return a boolean type. This way if a node is found with the given key you can return true or false.

    2) Or you can compare the items for both i.e

    else if(node.item == findNode(item).item) // assuming item is of primitive int type
    

    Hope it helps !