-1

I'm working on solving towers game by using stacks and linked lists and moving blocks from tower to tower by using recursion.

I encountered a problem in my problem which causes java.lang.NullPointerException. My guess why this was happening was that I try to pop value from a stack even when there are no entries. After I put bound control I still receive that error.

Th error points to the line with deleteFirst() method but I don't see why this would happens even after I check if lists are empty.

My task here was just to pass towers or LinkedStack objects then move the content of theirs in tower game fashion.

Errors:

Exception in thread "main" java.lang.NullPointerException
    at LinkList.deleteFirst(towers.java:47) // code with: **first = first.next;**
    at LinkedStack.pop(towers.java:82) // code with: return theList.deleteFirst();
    at LinkListApp.doTowers(towers.java:146) // code with: A.pop();
    at LinkListApp.doTowers(towers.java:140) // doTowers(a-1, A, C, B);
    at LinkListApp.main(towers.java:121) // doTowers(nDisks, linkA, linkB, linkC);

What am I doing wrong here? I can't make this work. as it should.

HelpNeeder
  • 6,383
  • 24
  • 91
  • 155

1 Answers1

2

Your doTowers call makes calls to A.pop() and C.pop(), neither of which is protected. Your LinkedStack directly calls theList.deleteFirst() without an empty check, and your deleteFirst method calls first = first.next without checking if first is null or not. It would be good to make your LinkedList smart enough that deleteFirst doesn't throw a NPE in this case, then you won't need special checks all over the place in the upper layers. To do that, change deleteFirst to something like

public long deleteFirst()
{
    if ( first != null ) {
        Link temp = first;
        first = first.next;
        return temp.dData;
    }
    else {
        return whateverIndicatesTheListIsAlreadyEmptyWhichMayBeHardWithReturnTypelong;
    }
}
digitaljoel
  • 26,265
  • 15
  • 89
  • 115
  • Yes, I tried that by wrapping pop method in if statement like this: `if (!A.isEmpty()) A.pop();`. But I still get null pointer exception. When I change to `if (A.isEmpty()) A.pop();` it never deletes fields, but with no errors. – HelpNeeder Oct 30 '12 at 18:55
  • This fixed the null pointer exception. I tried to check for this in doTowers method which didn't work. Thanks. Now, I just need to work on the output. – HelpNeeder Oct 30 '12 at 19:26