微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决图 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 举报,一经查实,本站将立刻删除。