0

At the moment I try to learn more about java and try to code a graph. I have a HashMap with . At the moment I want to implement a DFS but it won't work.

I want to add all nodes who are achievable from the startNode to a List

Is the code in principle correct or ok? I get a NullPointerException if I test my program. But I don't know why. I know a NPE is but in my mind my code shouldn't throw a NPE. So please don't mark it as duplicate from a NullPointer Question.

Thank you a lot for helping!

Here is my code:

/**
 * For a given node the method returns all nodes the outgoing edges of the node directly lead to.
 * 
 * @return list containing all directly connected nodes.
 */
@Override
public List<Node> getAdjacentNodes(Node startnode) {
    List<Node> nodes = null;
    if (startnode != null && this.nodes.values().contains(startnode)) {
        return startnode.getAdjacentNodes();
    }
    nodes = new LinkedList<Node>();
    return nodes;
}

@Override
public List<Node> getAdjacentNodes(int startnode) {
    return getAdjacentNodes(nodes.get(startnode));
}public List<Node> depthFirstSearch(Node startNode){
    LinkedList<Node> nodeList = null;
    resetState();

    //Get a List with all Adjacent Nodes from the startNode
    List<Node> node = getAdjacentNodes(startNode);
    //Test for each of the ADjacent Nodes from startNode if the current status is white
    for(Node child : node) {

        //Is the status white, run the recursive method
        if(child.status == Node.WHITE) {
            runDFS(child);
        }

    }

    return nodeList;
}

public LinkedList<Node> runDFS(Node child) {
    //Create a LinkedList as in the depthFirstSearch-Method
    LinkedList<Node> nodeList = null;
    //Set the status from the current child to GRAY
    child.status = Node.GRAY;
    //For each Child from the AdjacentsNodes from the child check if color is white
    for(Node nextNode : getAdjacentNodes(child)) {
        if (hasWhiteNeighbor(nextNode) == true) {
            //is color white execute the runDFS method again to get to the last node
            runDFS(nextNode);
        }
        //If the color is not white set it to black and add the node to List, because last node was found
        else {
            child.status = Node.BLACK;
            nodeList.add(child);
        }
    }
    return nodeList;
}
wit4r7
  • 125
  • 1
  • 13
  • please add the stacktrace – R Dhaval Jun 05 '17 at 16:05
  • What do you mean with stacktrace? (Sry. English is not my native language). I fixed the NullPointer Exception but the search and the add to the list won't work. – wit4r7 Jun 05 '17 at 16:08
  • ErrorLogs/ Exception .. Please give whole of it.. just saying NullPointerException cant help. – R Dhaval Jun 05 '17 at 16:11
  • Here seems a problem: `LinkedList nodeList = null;` . . `nodeList.add(child);` you called `add()` method withoud initializing `nodeList` `LinkedList`. – R Dhaval Jun 05 '17 at 16:29

0 Answers0