samedi 1 février 2020

Would someone be able to help point out why the logic is wrong in this Java code?

First time posting a question here on Stack! So I've been stuck on some logic problem with a while loop and if else statements involving Linked Lists in java. This piece of code is from an overall program. The program is a self - balancing (or attempting) binary search tree. What this section of code is supposed to do is read the first item from a linked list. If it doesn't fit the following property (if the Node has only one child) then it is removed from the list. If it does fit the property (that it only has one child) then I'm going to call a function based upon a series of conditions. My problem is occurring that when I try to remove the last element in the list. It gives me the "Index Out of Bounds" exception when trying to remove from the list meaning the list is empty, but I'm pretty sure I prevented it from moving on in the code if the list is empty. Maybe I'm wrong and I'm not sure. I might have some logic problem that I'm not seeing and would love another pair of eyes to look at it. I have the code posted below.

private void rebalanceTree(Node node) {

    LinkedList<Node> nodes = preorderTraversalNode();
    LinkedList<Integer> node_value = preorderTraversal();
    Node first_node;

    System.out.print(nodes.size() + " ");
    if(node_value.get(0) != null) {
        for(int index = 0; index < node_value.size(); index++) {
            System.out.print(node_value.get(index) + " ");
        }
    }

    if(nodes.get(0) != null) {
        first_node = nodes.get(0);
        while(first_node != null) {
            if((first_node.right == null && first_node.left == null) || (first_node.right != null && first_node.left != null))
                nodes.remove(0);
            else {
                if(first_node.right != null) {
                    if(first_node.right.right != null)
                        leftRotateTreeRR(first_node.right);
                    else if(first_node.right.left != null)
                        leftRotateTreeRL(first_node.right.left);
                } else if(first_node.left != null) {
                    if(first_node.left.left != null)
                        rightRotateTreeLL(first_node.left);
                    else if(first_node.left.right != null)
                        rightRotateTreeLR(first_node.left.right);
                }

                //System.out.print(nodes.size() + " ");
                nodes.remove(0); //This is the problem line

            }
        }
    } else {
        return;
    }

}

Aucun commentaire:

Enregistrer un commentaire