Java 使用双链接列表时的空指针
我正在尝试创建二维双链接圆形阵列,从txt文件读取数据并自动创建节点。我的程序正在正确地读取第一行,但当它到达下一行并开始创建下一个节点时,会出现空指针。我不明白为什么会这样,请帮帮我Java 使用双链接列表时的空指针,java,nullpointerexception,doubly-linked-list,Java,Nullpointerexception,Doubly Linked List,我正在尝试创建二维双链接圆形阵列,从txt文件读取数据并自动创建节点。我的程序正在正确地读取第一行,但当它到达下一行并开始创建下一个节点时,会出现空指针。我不明白为什么会这样,请帮帮我 public class project1 { public static void main(String[] args) { File file = new File("Input0.txt"); List mList = new List(); try
public class project1 {
public static void main(String[] args) {
File file = new File("Input0.txt");
List mList = new List();
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
Node kNode = new Node(line.charAt(0));
mList.insertLast(kNode);
for (int j = 1; j < line.length(); j++) {
System.out.println(line.charAt(j));
}
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class Node {
int data = 0;
char key;
Node nPrev, nNext, tNode, prev, next;
Node() {
}
Node(char c) {
key = c;
}
Node(Node x, Node p, Node q) {
tNode = x;
nPrev = p;
nNext = q;
}
Node(int x, Node p, Node q) {
data += x;
prev = p;
next = q;
}
}
class List {
Node head;
List() {
head = new Node();
head.prev = head;
head.next = head;
}
void insertFirst(char x) {
insertBefore(head.next, x);
}
void insertFirst(Node x) {
insertBefore(head.next, x);
}
void insertLast(char x) {
insertAfter(head.prev, x);
}
void insertLast(Node x) {
insertAfter(head.prev, x);
}
void insertAfter(Node pos, int i) {
Node n = new Node(i, pos, pos.next);
pos.next.prev = n;
pos.next = n;
}
void insertAfter(Node pos, Node x) {
Node n = new Node(x, pos, pos.next);
pos.next.prev = n;
pos.next = n;
}
void insertBefore(Node pos, int i) {
Node n = new Node(i, pos.prev, pos);
pos.prev.next = n;
pos.prev = n;
}
void insertBefore(Node pos, Node x) {
Node n = new Node(x, pos.prev, pos);
pos.prev.next = n;
pos.prev = n;
}
}
这些都是错误。
Null指针在尝试创建第二个节点时发生。它正确地创建第一个节点,而不是紧接着创建空指针
第77行=位置next=n
第69行=insertAfterhead.prev,x
第18行=mList.insertLastkNode 无法为新插入的节点设置指针:
void insertBefore(Node pos, int i) {
Node n = new Node(i, pos.prev, pos);
pos.prev.next = n;
pos.prev = n;
/** should contain also something similar to: **/
n.prev = pos;
n.next = pos;
}
实际上,在插入第一个节点时,您正在将head.prev设置为n,并将head.next设置为n。因此,在下一次插入时,您将传递n,即head.next,并尝试使用n.prev==null调用n.prev.next,n.prev后面的行再次为null。请发布完整的代码。您遗漏了insertBeforenode、char函数定义。