0

So I am trying to make a program that uses linked list. I am getting a runtime error when I try to run it though. I am completely confused and have literally no idea on how to fix this. There is apparently something wrong with my traversal method in MyLinkedList class.

Error: Exception in thread "main" java.lang.NullPointerException at MyLinkedList.traversal(MyLinkedList.java:68) at MyLinkedListClient.main(MyLinkedListClient.java:13)

It highlights this line of code: result = temp.getElement() + "-->";

I apologize if I have asked this in a poorly written manner. My 2nd time using this website so hopefully I do not chewed out too badly >< lol Oh and sorry if my code is formatted weird, it got weird trying to get it to look like code in my post lol.

Any help is greatly appreciated.

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
  • Most likely the immediate cause is that the `temp` variable is `null` and you are trying to dereference it. However, the fastest way to get to the root cause of _your_ code is probably to use a debugger and see what is wrong. – Tim Biegeleisen Nov 12 '15 at 00:41
  • 1
    When the list is empty, you never assign the new node to `head`, so the list never has a head node and is always empty (according to your `isEmpty` method) – MadProgrammer Nov 12 '15 at 00:47
  • You don't need the if else statement in addFirst. Just do temp.setNext(head); head = temp; – Atri Nov 12 '15 at 00:58

0 Answers0