public class MySingleList implements MyList {
class Node {
E item;
Node next;
Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
private Node<E> head;
private int size;
@Override
public void add(E item) {
Node<E> node = new Node<>(item, null);
Node<E> tail = getTail();
if (tail == null)
this.head.next = node;
else
tail.next = node;
this.size++;
}
private Node<E> getTail() {
if (this.head==null) {
return null;
} else {
Node<E> p = this.head;
while (p.next != null) {
p = p.next;
}
return p;
}
}
@Override
public E get(int index) {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public E remove(int index) {
return null;
}
public static void main(String[] args) {
MySingleList<String> msl = new MySingleList<>();
msl.add("21");
// msl.add("215");
System.out.println(msl.head.item);
}
}
老是会在add函数那报空指针异常,真的难受
你head没有初始化,对Null调用.next自然会报空指针