0

I'm pretty new to java, and my doubly linked list addFront method and addRear method works fine, but only dequeue method doesn't works. In the main method, I making a test to remove front element using dequeueFront ()method, when I remove front element it works, but If I continued removing front element,

Exception in thread "main" java.lang.NullPointerException
    at DoublyLinkedDeque.dequeueFront(DoublyLinkedDeque.java:97)

comes out,

Line97 is the frontNode.previous=null

I just wondering how to remove front element form the double linked list properly.

public E dequeueFront() throws NoSuchElementException 
{
    if(frontNode!=null)
    {
        E frontElement=frontNode.element;
        frontNode=frontNode.next;
        frontNode.previous=null;
        frontNode.next=null;
        numElement--;
        if(numElement==0)
            rearNode=null;
        return frontElement;
    }
    else
        throw new NoSuchElementException();
}
Rajeev Singh
  • 3,292
  • 2
  • 19
  • 30
J.Cool
  • 45
  • 4

2 Answers2

0
 frontNode=frontNode.next;

If there is no next after frontNode, then frontNode.next returns null.

If frontNode is null then trying to do:

 frontNode.previous=null;

Will throw a null pointer exception because how can you access the previous node from a node that doesn't exist? Without thinking about how to make it work with your implementation, just doing a null check will stop this from happening.

if(frontNode != null){
    frontNode.previous = null;
}

You will have to do this check with the ".next" also

Or, maybe you can check if numElements = 1. I'll let you think of how to solve that problem.

Brandon Ling
  • 3,841
  • 6
  • 34
  • 49
0

It should look more like

public E dequeueFront() throws NoSuchElementException {
if(frontNode!=null)
{
    E frontElement=frontNode.element;
    N oldFront = frontNode ;
    frontNode=oldFront.next; // frontNode may now be null
    if( frontNode != null ) frontNode.prev=null; // remove link to oldFront
    oldFront.previous=null; // should be unessary
    oldFront.next = null ;

    numElement--;
    if(numElement==0)
        rearNode=null;
    return frontElement;
}
else
    throw new NoSuchElementException();
}
J Bauer
  • 1
  • 1