当我运行以下代码时,我得到空指针异常。我无法弄清楚为什么会这样。
public class LinkedList<T> {
private Link head = null;
private int length = 0;
public T get(int index) {
return find(index).item;
}
public void set(int index, T item) {
find(index).item = item;
}
public int length() {
return length;
}
public void add(T item) {
Link<T> ptr = head;
if (ptr == null) {
// empty list so append to head
head = new Link<T>(item);
} else {
// non-empty list, so locate last link
while (ptr.next != null) {
ptr = ptr.next;
}
ptr.next = new Link<T>(item);
}
length++; // update length cache
}
// traverse list looking for link at index
private Link<T> find(int index) {
Link<T> ptr = head;
int i = 0;
while (i++ != index) {
if(ptr!=null) {
ptr = ptr.next;
}
}
return ptr;
}
private static class Link<S> {
public S item;
public Link<S> next;
public Link(S item) {
this.item = item;
}
}
public static void main(String[] args) {
new LinkedList<String>().get(1);
}
}