0

Pretty new coder here.. Working on the Princeton algorithms one course and I'm attempting the "Stack with max" assignment.

public class Stack {
    
    private Node first = null;
    
    private class Node {
        int item;
        Node next;
    }
    
    public void push(int item, Stack max) {
        Node oldFirst = first;
        first = new Node();
        first.item = item;
        first.next = oldFirst;
        // if the first value is null put it to max stack
        if(first == null) {
            max.first.item = item;
            max.first.next = oldFirst;
        }
        // otherwise if the item is greater than the max stack's top value, add it to the max stack
        else if(item >= max.first.item) {
            max.first.item = item;
            max.first.next = oldFirst;
        }
    }
    
    public int pop(Stack max) {
        int item = first.item;
        first = first.next;
        // if the item removed is the max value (top of max stack) then also remove it from the max stack
        if(item == max.first.item) {
            max.first = max.first.next;
        }
        return item;
    }
    
    public static void main(String[] args) {
        Stack allValues = new Stack();
        Stack maxValues = new Stack();
        
        allValues.push(3, maxValues);
    }
}

Whenever I run the code, I get a nullpointerexception pointing to line 22.

else if(item >= max.first.item)

I'm not sure why this is happening as I'm only trying to push an item into the max stack when the first item is not null. Any help would be greatly appreciated. Thank you :)

badCoder00
  • 11
  • 2
  • `if(first == null)` first will never be null. I think you meant `max.first` on `line 17` i think – papaya Oct 27 '20 at 06:07
  • `max.first` is null when `max` is just created with `new Stack()`, and you're dereferencing it, which causes the NullPointerException. I don't understand your logic, but maybe you need to check that it's also not null `if(max.first != null && item >= max.first.item)`? – ernest_k Oct 27 '20 at 06:07
  • you max.first undefined you must initiliaze max.first – Mehmet Onar Oct 27 '20 at 06:27
  • Thank you all for the help! I ended up figuring it out. :) – badCoder00 Oct 27 '20 at 15:06

0 Answers0