I cant figure out why the minCheck function in the MinStack class does not successfully update the value of minVal when it is called from the push function. Ignore logical error that if minVal is popped, minVal's value will not represent the actual min value.
public class MinStack {
int[] array; //array to hold elements
int n = 0; // number of elements in array
int minVal=10000; // smallest value in array (initialize to 1000 to prove it wont change)
public int size() { //ignore this useless method
return n;
}
public void push(int x) {
if((n+1)>array.length)
resize();
array[n] = x;
n++;
minCheck(x); // minCheck will check if x is the new smallest value, and set minVal = x if it is.
}
public int pop() {
int x = array[n-1];
n--;
return x;
}
public void minCheck(int x) {
if(n==1)
minVal = x; //if x is the only element in the array, it must be the minVal
else {
if(minVal>x) //if x is smaller than current minVal, it becomes the minVal
minVal = x;
}
}
private void resize() { //method not relevant to the question
int[] secondArray = new int[(Math.max(1, n * 2))];
for(int i=0; i<n; i++) {
secondArray[i] = array[i];
}
array = secondArray;
}
public String printMinVal() {
return "minimum value is: " + minVal;
}
public static void main(String[] args) {
MinStack myStack = new MinStack();
try {
myStack.push(3);
myStack.push(2);
myStack.push(1);
myStack.push(4);
myStack.push(5);
myStack.pop();
} catch(NullPointerException e) {};
System.out.println(myStack.printMinVal()); //would expect to get "minimum value is 1" as console output, but instead get "minimum value is 1000"
}
}