sorry if this formatted a bit oddly, this is my first time asking a question here. I am working on a method for my class that is supposed to add a new node containing a specified value to the end of a linked list. However I keep seeing a NullPointerException at the start of my while loop. I would really appreciate any insight.
public void add(Anything value)
{
Node temp = first;
if (temp==null) {
this.addFirst(value);
}
while(temp.next!=null){
temp=temp.next;
}
temp.next=new Node(value, null);
}
Note: for the purposes of this assignment I am only creating methods, the assignment is preloaded with some code already that I am not allowed to change. I have attached it to provide some more detail.
public class CS2LinkedList<Anything>
{
// the Node class is a private inner class used (only) by the LinkedList class
private class Node
{
private Anything data;
private Node next;
public Node(Anything a, Node n)
{
data = a;
next = n;
}
}
private Node first;
private Node last;
public CS2LinkedList()
{
first = null;
}
public boolean isEmpty()
{
return (first == null);
}
public void addFirst(Anything d)
{
Node temp = first;
first = new Node(d,temp);
}
public void clear()
{
first = null;
}
public boolean contains(Anything value)
{
for (Node curr = first; curr != null; curr = curr.next)
{
if (value.equals(curr.data)) {
return true;
}
}
return false;
}
public String toString()
{
StringBuilder result = new StringBuilder(); //String result = "";
for (Node curr = first; curr != null; curr = curr.next)
result.append(curr.data + "->"); //result = result + curr.data + "->";
result.append("[null]");
return result.toString(); //return result + "[null]";
}
}
Thank you!