首页 > 解决方案 > 广度优先搜索 - 空指针异常

问题描述

我已经实现了一个学校项目的广度优先搜索,我将方向图的起始节点作为输入,我必须返回一个包含 BFS 顺序节点的链接列表

这是我的方法:

public List<Node> breadthFirstSearch(Node startNode){

    //node list that has to be returned  
    LinkedList<Node> nodeList = new LinkedList<Node>();

    resetState();

    // TODO

    //Queueu for the DfS Algorithm 
    Queue<Node> nodeQueue = new LinkedList<Node>();

    //Add start node to NodeList and Queue
    nodeQueue.add(startNode);
    nodeList.add(startNode);

    //While the Queue isn't empty
    while(!nodeQueue.isEmpty()) {
        Node v = nodeQueue.poll();
        //iterate over adjacent nodes of current node and add them to Queue and List 
        for (Node w : getAdjacentNodes(v)) {
            //don't add if already traversed node
            if (!nodeList.contains(w)) {
                nodeList.add(w);
                nodeQueue.add(w);
            }
        }
    }

    return nodeList;
}

我已经为几个图表测试了我的函数,并且在我自己的测试中没有得到任何错误。但是当我将我的代码上传到学校服务器并运行他们的测试时,我得到了以下错误:java.lang.NullPointerException in SearchTestng.testBFSCliqueNodes(SearchTestng.java:512) 我已经尝试重现这个问题好几个小时了,我的导师似乎都不知道是什么导致了异常。

你们中有人知道什么可能导致这里出现空指针异常吗?

标签: javanullpointerexceptionqueuegraph-theorybreadth-first-search

解决方案


推荐阅读