I've an implementation of a stack which aside from push, peek and pop returns the max Value. Here's my code.
static class MaxStack{
private Node top;
private Node maxTop;
private class Node{
int data;
Node next;
Node(int item){
this.data = item;
this.next = null;
}
}
void push(int item){
Node p = new Node(item);
if(top == null){
top = p;
Node q = new Node(item);
maxTop = q;
return;
}
p.next = top;
top = p;
if(item > maxTop.data){
Node q = new Node(item);
q.next = maxTop;
maxTop = q;
}
}
void pop(){
if(top == null) throw new IllegalStateException("Popping off and empty stack");
top = top.next;
if(top.data == maxTop.data){
maxTop = maxTop.next;
}
}
int peek(){
return top.data;
}
int peekMax(){
return maxTop.data;
}
In my client code when I use this class, I get a Null Pointer Exception
in the pop method.
Can someone help me understand what's wrong here.