I am getting a null pointer exception before I can even get to my code. I cannot tell if it will work correctly cause I can’t make it pass this point.
The error is thrown in this line:
if(currentNode.getData() > currentNode.getNext().getData())
Here is my bubble sort:
public static void bubbleSort(DoubleLinkedList list) //static method used to sort the linked list using bubble sort
{
int i = 0;
int j = 0;
Node currentNode = list.head;
Node previousNode = currentNode;
Node tempNext = currentNode;
Node tempPrevious = currentNode;
for(i=1; i<list.getSize(); i++)
{
for(j=0; j<list.getSize()-1; j++)
{
if(currentNode.getData() > currentNode.getNext().getData())
{
if(currentNode == list.head)
{
Node tempNode = currentNode.getNext();
list.head = tempNode;
tempNext = tempNode.getNext();
tempNode.setNext(currentNode);
currentNode.setNext(tempNext);
currentNode.setPrevious(tempNode);
tempNext.setPrevious(currentNode);
}
else if(currentNode.getNext() == list.last)
{
Node tempNode = currentNode.getNext();
list.last = currentNode;
tempPrevious = currentNode.getPrevious();
tempNode.setNext(currentNode);
tempNode.setPrevious(tempPrevious);
currentNode.setPrevious(tempNode);
}
else
{
Node tempNode = currentNode.getNext();
tempPrevious = currentNode.getPrevious();
tempNext = currentNode.getNext();
tempPrevious.setNext(tempNode);
tempNext.setPrevious(currentNode);
currentNode.setNext(tempNext);
tempNode.setPrevious(tempPrevious);
}
}
currentNode = currentNode.getNext();
}
}
}
I thought the limits on my loops would keep the compiler from trying to access a pointer that does not necessarily exist which is what I understand a null pointer exception to be.
If anyone could help me get past this error so that I can test my bubble sort I’d be extremely grateful!
Either
currentNodeis null orcurrentNode.getNext()returns null and that’s why you cant callgetData()on it. You should always check your nodes for null values before you use them.