BST中的Java NullPointerException

时间:2017-01-13 13:14:50

标签: java nullpointerexception

我为Binary Search Tree制作了一个代码。它只有Insert功能。我在insert()函数while条件下收到错误。

Exception in thread "main" java.lang.NullPointerException
    at tree.LinkNode.insert(BST.java)
    at tree.BST.main(BST.java)

我已使用关键字stub初始化insert()函数中的动态变量new

我哪里出错了?

代码有三个类:

  1. BST (包含main()类)
  2. LinkNode (包含LinkNode引用和insert()函数)
  3. MyLinkNode (初始化根节点的类)
  4. 代码:

    public class BST {
    
        public static void main(String[] args){
        MyLinkNode start = new MyLinkNode(42);
        LinkNode node = new LinkNode();
        node.insert(start.root, 36);
        }
    }
    
    class LinkNode{
    
        LinkNode leftnode;
        LinkNode rightnode;
        LinkNode parentnode;
        int value;
    
    
        public LinkNode() {}
    
    
        public String insert(LinkNode root, int val){
            LinkNode stub = new LinkNode();
            stub = root;
            while(stub.leftnode == null || stub.rightnode == null){
                if(stub.value < val){
                    stub = stub.leftnode ;
                }
                else if(stub.value > val){
                    stub = stub.rightnode;
                }
                else{
                    System.out.println("You Cannot insert a value that already exist in the tree.\nPlease insert a different value");
                    return "";
                }
            }
            stub.value = val;
            stub.leftnode = null;
            stub.rightnode = null;
            this.parentnode = stub;
            return "Insertion Succesful";
        }
    }
    
    class MyLinkNode{
    
        LinkNode root;
    
        public MyLinkNode(int val){
            root = new LinkNode();
            root.value = val;
            root.parentnode = null;
            root.leftnode = null;
            root.rightnode = null;
        }
    }
    

0 个答案:

没有答案