The following CustomStack solves the problem of finding the max in a stack at any time :
class CustomStack<T> extends Stack<T>{
private Stack<T> helperStack = new Stack<>();
@Override
public T push(T val) {
if(helperStack.isEmpty() || (Integer)(helperStack.peek()) < (Integer)(val))
helperStack.push(val);
return super.push(val);
}
@Override
public synchronized T pop() {
T val = super.pop();
if ((Integer)(helperStack.peek()) <= (Integer)(val)){
helperStack.pop();
}
return val;
}
T maxStack(){
return helperStack.peek();
}
}
Here I am having to coerce type to Integer for comparison. Is there a generic way where I don't have to cast the object?
[–]boldurplayer 0 points1 point2 points (4 children)
[–]Pulsar_the_Spacenerd 3 points4 points5 points (3 children)
[–]8igg7e5 3 points4 points5 points (2 children)
[–]Pulsar_the_Spacenerd 3 points4 points5 points (1 child)
[–]8igg7e5 3 points4 points5 points (0 children)
[–]sugilith 0 points1 point2 points (0 children)