图 BFS 实现问题在尝试入队时返回空指针异常

问题描述

我目前正在学习数据结构和算法,并想尝试实现一个图形,但是当我尝试在一些在线资源的帮助下实现 BFS 时,我被卡住了,因为我无法将我的 int 作为 root 加入队列。

我的图表代码:

public class DSAGraph {
int vertex;
public DSALinkedList lList[];
public DSAQueue queue;

//initialize a graph
//every single vertex create a new linked list hence for loop
public DSAGraph(int vertex)
{
    this.vertex = vertex;
    lList = new DSALinkedList[vertex];
    for(int i = 0; i<vertex; i++)
    {
        lList[i] = new DSALinkedList();
    }
}


//create edge link between nodes
public void addEdge(int start,int destination)
{
    lList[start].insertFirst(destination);
    lList[destination].insertFirst(start);
}

BFS:

public void BFS(int index)
{
    boolean visited[] = new boolean[vertex];
    int a = 0;
    
    visited[index] = true;//mark true after visit
    queue.enqueue(index); <-- return null pointer Exception
    
    while(queue.size()!=0)
    {
        index = (int)queue.poll();
        System.out.print(index);
    }
    
    for(int i =0; i<lList[index].size(); i++)
    {
        a = (int)lList[index].get(i);
        if(!visited[a])
        {
            visited[a] = true;
            queue.enqueue(a);
        }
    }
}

我的入队:

public void enqueue(Object data)
{
    qList.insertLast(data);
    
    counter ++;
}

在链表中插入最后一个:

void insertLast(Object val)
{
    Node newNode = new Node();
    newNode.m_value = val;
    if(isEmpty())
    {
        head = newNode;
    }
    else
    {
        tail.m_next = newNode;
        newNode.m_prev = tail;
    }
    tail = newNode;
    counter++;
}

主要:

public static void main(String[] args)
{
    DSAGraph graph = new DSAGraph(4);
    graph.addEdge(0,1);
    graph.addEdge(1,2);
    graph.addEdge(2,3);
    graph.BFS(0);
}

我是否错过或误解了此处的某些内容?提前感谢您的回复!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...