使用双向链表时为空指针 [英] Null pointer when using doubly linked list
问题描述
我正在尝试创建二维双向链接的圆形数组,从txt文件读取数据并自动创建节点。我的程序正在正确读取第一行,但是当它到达下一行并创建下一个节点的时间时,会出现空指针。我不明白为什么会这样。
I am trying to create 2d doubly linked circular array, reading data from a txt file and creating nodes automatically. My program is reading the first line properly, but when it reaches next line and time to create next node, null pointer occurs. I dont understand why it is happening please help me.
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;
}
}
这些是错误。
空指针在尝试创建第二个节点时发生。
these are the error. Null pointer happens when its trying to create second node. it creates first node properly than says Null pointer right after.
第77行= pos.next = n;
line 77 = pos.next = n;
第69行= insertAfter(head.prev,x);
line 69 = insertAfter(head.prev, x);
第18行= mList.insertLast(kNode);
line 18 = mList.insertLast(kNode);
推荐答案
您缺少为新插入的节点设置指针的方法:
You are missing to set the pointers for the newly inserted node:
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;
}
实际上,当您插入要设置头的第一个节点时,您正在做什么。上一个和下一个。因此,在下一次插入时,您要传递n(现在为head.next),并尝试使用n.prev == null和n.prev之后的行再次调用null来调用n.prev.next。
Actually what you are doing when inserting the first node you are setting your head.prev to n and your head.next to n. So at the next insert you are passing n (which is head.next now) and try to invoke n.prev.next with n.prev == null and the line following n.prev which again is null.
这篇关于使用双向链表时为空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!