0

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.

Zeus
  • 2,213
  • 8
  • 28
  • 45
  • Perhaps maxTop is null. Check for it. – Indy Mar 05 '16 at 19:59
  • You are getting a null pointer in pop(). Once you check for null in top, you set it equal to top.next. Then you again access top.data. Consider the case where your stack contains just one element. In this case, top.next is null, which essentially means that you are trying to access null.data which throws the exception. – alpha_ulrich Mar 05 '16 at 20:38

0 Answers0