Singly linked list delete() method
That's a very lengthly piece of code. To delete a Node, it's not about doing something confusing; it's about changing links around. Imaging this list:

1, 2, 3, 4, 5


In this case, 1 links to 2, which links to 3, and so on. So what if you want to remove 3, for example? Well, change the links so that 2 links to 4!

How? Well...


Rewrite the method so that it returns a boolean depending on if the delete was a success:

public boolean delete(int data) {

Handle special case head and empty list:

    SinglyLinkedNode nodeBeforeDelete = this.head;
    if (nodeBeforeDelete == null) { // List in empty
        return false;
    } else if (nodeBeforeDelete.getData() == data) {
        this.head = this.head.getNext();
        return true;
    }

Loop until you find the data:

    while (true) {
        SinglyLinkedNode next = nodeBeforeDelete.getNext()
        if (next == null) { // No data found in list
            return false;
        } else if (next.getData() == data) {
            break;
        }
        nodeBeforeDelete = next;
    }

Relink the nodes:

    SinglyLinkedNode next = nodeBeforeDelete.getNext();
    nodeBeforeDelete.setNext(next.getNext());
    next.setNext(null);

End the method:

    return true;
}



Result:

    public boolean delete(int data) {
        SinglyLinkedNode nodeBeforeDelete = this.head;
        if (nodeBeforeDelete == null) { // List in empty
            return false;
        } else if (nodeBeforeDelete.getData() == data) {
            this.head = this.head.getNext();
            return true;
        }
        while (true) {
            SinglyLinkedNode next = nodeBeforeDelete.getNext()
            if (next == null) { // No data found in list
                return false;
            } else if (next.getData() == data) {
                break;
            }
            nodeBeforeDelete = next;
        }
        SinglyLinkedNode next = nodeBeforeDelete.getNext();
        nodeBeforeDelete.setNext(next.getNext());
        next.setNext(null);
        return true;
    }