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 :)