Click to See Complete Forum and Search --> : Stack List


doucettej3
March 17th, 2010, 08:05 PM
Im trying to make a stack with its top entry at the end of a chain of linked nodes. When I run it, I get a null pointer exception.
public class StackList<T> implements StackInterface<T> {
private Node firstNode; // reference to first node
private Node lastNode; // reference to last node
private int length = 0; // number of entries in list

public StackList(){
firstNode = null;
lastNode = null;
}
public void push(T newEntry){
Node newNode = new Node (newEntry, lastNode, firstNode);
if(length<1)
{
firstNode = newNode;

lastNode = firstNode;

}else
{lastNode = newNode;
}length++;
}
public T pop(){
{
T result = peek ();
if (lastNode != null)

assert !isEmpty ();
if (length == 1)
{
firstNode = firstNode.next;
lastNode = null; // solitary entry was removed
}
else
{
Node nodeBefore = GetNodeAt (length - 1);
Node nodeToRemove = nodeBefore.next;
Node nodeAfter = nodeToRemove.next;
nodeBefore.next = nodeAfter; // disconnect node to be removed

lastNode = nodeBefore; // last node was removed
} // end if
length--;
return result;
}

}

public T peek(){ T result = null;
if (lastNode != null)
result = lastNode.getData();
System.out.print(lastNode.getData() +" ");
return result;
}


This is my output: 10 hello blah Exception in thread "main" java.lang.NullPointerException
at StackList$Node.access$1(StackList.java:83)
at StackList.pop(StackList.java:42)
at StackList.main(StackList.java:114)
any help would be great.

dlorde
March 18th, 2010, 06:04 AM
The exception error message tells you where the problem is (StackList.java line 83).

Unfortunately you haven't posted all the relevant code, and you haven't explained what operations you were doing when it failed, so it's hard to make any further comment...

However, the peek method has an obvious bug - you check for lastNode being null before calling getData on it, but then you try to print out the data using the same call when it could be null.

Controlling complexity is the essence of computer programming...
B. Kernighan