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

如何在java中创建一个链表数组?

所以我需要像这样输入一个二分图的边:
6
1 3
1 2
1 5
2 7
2 4
2 9

一个数字是边数.之后列出边.看到如何顶点1有多个不同的边缘,我想跟踪1连接到什么,我在想,图的每个顶点都会有一些列表,它连接的顶点,导致我尝试创建一个链表的数组,但我不知道该怎么做.我试过了

LinkedList<Integer>[] vertex = new LinkedList[5];
int i = 0,m = 6;
while(i!=m){
    int temp = sc.nextInt();
    int temp2 = sc.nextInt();
    vertex[temp].add(temp2);
    i++;
}

但是我在加法行得到一个nullpointerexception.

解决方法

LinkedList<Integer>[] vertex = new LinkedList[5];
int i = 0,m = 6;
while(i!=m){
  int temp = sc.nextInt();
  int temp2 = sc.nextInt();

  // Make sure the list is initialized before adding to it
  if (vertex[temp] == null) {
     vertex[temp] = new LinkedList<Integer>();
  }

  vertex[temp].add(temp2);
  i++;
}

原文地址:https://www.jb51.cc/java/120660.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐