java中空指针异常问题
package dataStruct;
import java.util.Random;
public class LineLink {
private Node head;
private int nElems;
public LineLink(){
head = null;
nElems = 0;
}
public boolean isEmpty(){
return nElems == 0;
}
public boolean insert(int x){
return insert(x,nElems);
}
public boolean insert(int x,int index){
if (index < 0 || index > nElems) {
System.out.println("待插入元素的索引号超过范围");
return false;
}
Node n = new Node(x);
if(head == null){
head = n;
}else{
Node p = head;
int count = 0;
while(count < index){
p = p.next;
count ++;
}
n.next = p.next;
p.next = n;
}
nElems ++;
return true;
}
public Node find(int key){
if(isEmpty()){
System.out.println("对不起,此链表是空的,无数据可查");
return null;
}else{
Node current = head;
int count = 0;
while(current.data != key){
if(current.next == null){
System.out.println("对不起,此链表中没有您要查找的数据");
return null;
}else{
current = current.next;
count ++;
}
}
System.out.println("您要查找的数据在此链表中的"+count+"位置");
return current;
}
}
public Node remove(int x){
return remove(x,nElems);
}
public Node remove(int x,int index){
if (index < 0 || index > nElems - 1 || nElems == 0) {
System.out.println("待删除元素的索引号超过范围或表已空");
return null;
}else{
Node current = head;
Node temp = head;
int count = 0;
while(count < index && current.data != x){
if(current.next == null){
System.out.println("对不起,此链表中没有您要查找的数据");
return null;
}else{
temp = current;
current = current.next;
count ++;
}
}
temp.next = current.next;
current.next = null;
return current;
}
}
public void display() {
if (nElems > 0) {
Node p = head;
while (p != null) {
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
} else {
System.out.println("这是一个空表");
}
}
public static void main(String[] args){
LineLink link = new LineLink();
Random ran = new Random();
link.display();
for(int i = 0; i < 20; i ++){
link.insert(ran.nextInt(50));
}
link.display();
}
}
class Node{
public int data;
public Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
运行后抛出:
Exception in thread "main" java.lang.NullPointerException
at dataStruct.LineLink.insert(LineLink.java:32)
at dataStruct.LineLink.insert(LineLink.java:15)
at dataStruct.LineLink.main(LineLink.java:101)