为什么我在进行链表遍历时会收到java.lang.NullPointerException?

时间:2015-11-12 00:37:41

标签: java linked-list stack runtime-error traversal

所以我试图制作一个使用链表的程序。我尝试运行它时遇到运行时错误。我完全感到困惑,并且根本不知道如何解决这个问题。在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

0 个答案:

没有答案