linked list null pointer exception
I am trying to create a Linked List class for my programming homework. I need to make my insert method perform the lookup method first so that I cannot insert any duplicate elements. the code works and compiles fine without my if(lookup==false) conditional, but with my current code below I get a null pointer exception at temp.data.equals(x) in the lookup method. Here is my linkedlist class:
Code :
public class linkedList implements myLinkedList
{
public myNode head = null;
public myNode tail = null;
public myNode temp = null;
public linkedList()
{
myNode node = new myNode();
node = null;
}
//inserts objects to the end of the list if not already there
public void insert(Object x)
{
if(lookup(x) == false)
{
if(head==null)
{
head = new myNode();
tail = new myNode();
head.data = x;
head.next = tail;
tail = head;
}
else
{
tail.next = new myNode();
tail = tail.next;
tail.data = x;
}
}
}
public void delete(Object x)
{
}
public boolean lookup(Object x) //interface in lab says public Object, but directions specify for it to return boolean value
{
temp = head;
while(temp != null)
{
if(temp.data.equals(x)) return true;
temp = temp.next;
}
return false;
}
public boolean isEmpty()
{
if(head==null) return true;
else return false;
}
public void printList()
{
myNode index = head;
while(index != null)
{
System.out.println(index.data.toString());
index = index.next;
}
}
}
this will work the first time i try to insert an object, but any subsequent attemps result in the null pointer exception. I am not sure what the problem is, any advice would be extremely helpful
Re: linked list null pointer exception
where does the nullpointer points out in your line of code? , in that way you/we can determine or atleast have a clue to what causes the exception.. i think its on the constructor of your class
Re: linked list null pointer exception
Quote:
I get a null pointer exception at temp.data.equals(x) i
What variable has a null value? Find which one and then backtrack in the code to see why that variable does not have a valid value.