我知道这并不复杂,但由于某种原因我无法弄清楚。
我试图将一个元素插入到双向链表中,并保持一切排序。我查找了一些与此类似的不同问题,但似乎没有一个完全相同。
简单地说,如果我有一个双向链表: 3 <-> 4 <-> 5 <-> 7 <-> 8
insertMid(6): 3 <-> 4 <-> 5 <-> 6 <-> 7 <-> 8
public void insert(IndexRecord newRec){
Node newNode = new Node(newRec);
Node curNode = front;
if (isEmpty()){ //Empty list
front = newNode;
}else if (front.getNext() == null){ //One element in list
newNode.setPrev(front);
front.setNext(newNode);
back = newNode;
back.setPrev(front);
}else if (back.compareTo(newNode) < 0){ //New node is greater than back
back.setNext(newNode);
newNode.setPrev(back);
back.getPrev().setNext(newNode);
back = newNode;
}else{ //New node is in between two others
while (curNode != null){
if (newNode.compareTo(curNode) < 0){
curNode = curNode.getNext();
}else{
break;
}
}
newNode.setNext(curNode);
newNode.setPrev(curNode.getPrev());
curNode.getPrev().setNext(newNode);
curNode.setPrev(newNode);
}
}
它只是在 curNode.getNext().setPrev(newNode()); 线上给了我一个 NPE;但是如果我在我的while循环条件中检查它怎么会发生呢?