1

I'm attempting to implement bubble sort for dual linked lists, but I get a NullPointerException.

Here is the code:

public void bubbleSort()
{           
    DLLNode<E> tmp = this.first; // (1)
    DLLNode<E> tmp2 = null; // (1)
    boolean flag = true;
    while(flag)
    {
        // (2)
        flag = false;
        while(tmp.succ!=null)
        {

            if(tmp.element2.compareTo(tmp.succ.element2)<0)
            {
                tmp2.element2 = tmp.element2;
                tmp.element2 = tmp.succ.element2;
                tmp.succ.element2 = tmp2.element2;
                tmp2.element1 = tmp.element1;
                tmp.element1 = tmp.succ.element1;
                tmp.succ.element1 = tmp2.element1;
                flag = true;
            }
            tmp = tmp.succ;
        }
    }
}

Another thing: this method that I used I think will iterate the list only once, and won't turn back at the beginning. I thought moving tmp and tmp2 from (1) to (2) would solve the problem. But I still receive a NullPointerException.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
VL4DiMiRG
  • 67
  • 1
  • 2
  • 8

1 Answers1

0

This line seems to be the problem:

DLLNode<E> tmp2 = null; // (1)

Here, you've created a null pointer. A few lines later, without any further assignments to tmp2, you attempt to access tmp2.element2 using this null pointer, which crashes the program:

tmp2.element2 = tmp.element2;

Re-evaluate your design and ensure all of your objects have been initialized before trying to access their properties or methods.

ggorlen
  • 44,755
  • 7
  • 76
  • 106