所以我试图制作一个使用链表的程序。我尝试运行它时遇到运行时错误。我完全感到困惑,并且根本不知道如何解决这个问题。在MyLinkedList类中,我的遍历方法显然有问题。
错误:Exception in thread "main" java.lang.NullPointerException
at MyLinkedList.traversal(MyLinkedList.java:68)
at MyLinkedListClient.main(MyLinkedListClient.java:13)
它强调了这一行代码:result = temp.getElement() + "-->";
非常感谢任何帮助。
public class MyLinkedListClient {
public static void main(String [] args) {
MyLinkedList<String> myList = new MyLinkedList<String>();
myList.addFirst("MSP");
myList.addFirst("RST");
myList.addFirst("LAX");
myList.addFirst("PHL");
System.out.println(myList.traversal());
System.out.println(myList.removeFirst() + " is removed.");
System.out.println(myList.traversal());
}
}//end of class
public class MyLinkedList<E> {
//instance variables
private Node<E> head;
//private Node<E> tail
private int size;
//constructor
public MyLinkedList() {
head = null;
//do something with tail
size = 0;
}
public boolean isEmpty() {
if(head == null)
return true;
return false;
}
public int size() {
return size;
}
public void addFirst (E element) {
Node<E> temp = new Node<E>(element, null);
//do something with tail
if(isEmpty())
temp.setNext(head);
else {
temp.setNext(head);
head = temp;
}
size++;
}
public E removeFirst() throws EmptyListException {
if(isEmpty())
throw new EmptyListException("The list is empty.");
Node<E> temp = head; //step 1
head = head.getNext(); //step 2
temp.setNext(null); //step 3
size--;
return temp.getElement(); //step 4
}
public String traversal() {
if(size() == 0)
return "Empty list.";
Node<E> temp = head;
String result = "Head -->";
int i = size();
while (i > 0) {
result = temp.getElement() + "-->";
temp = temp.getNext();
i--;
}
return result;
}
/*
public boolean search( E element) {
}
*/
}//end of class