问题
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.
line 77 = pos.next = n;
line 69 = insertAfter(head.prev, x);
line 18 = mList.insertLast(kNode);
回答1:
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;
}
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.
来源:https://stackoverflow.com/questions/21224445/null-pointer-when-using-doubly-linked-list