Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.
Looking for code review, optimizations, best practices.
public class StackMinimum<T>{
/*
* Composition triumphs over inheritance :)
*/
private final Stack<T> stack1 = new Stack<T>();
private final Stack<T> stack2 = new Stack<T>();
public void push(T item) {
stack1.push(item);
if (stack2.isEmpty() || ((Comparable<T>) item).compareTo(stack2.peek()) < 0) {
stack2.push(item);
}
}
public T pop() {
T item = stack1.pop();
if (item.equals(stack2.peek())) {
stack2.pop();
}
return item;
}
public T peek() {
return stack1.peek();
}
public int size() {
return stack1.size();
}
public T getMinimum () {
return stack2.peek();
}
public boolean isEmpty() {
return stack1.isEmpty();
}
}
public class StackMinimumTest {
@Test
public void test() {
StackMinimum<Integer> stack1 = new StackMinimum<Integer>();
stack1.push(1);
stack1.push(2);
stack1.push(3);
assertEquals(1, (int)stack1.getMinimum());
stack1.push(-1);
assertEquals(-1, (int)stack1.getMinimum());
stack1.pop();
assertEquals(1, (int)stack1.getMinimum());
while(!stack1.isEmpty()) {
assertEquals(1, (int)stack1.getMinimum());
stack1.pop();
}
}
}
StackMinimum<T extends Comparable<T>>
. Don't cast. \$\endgroup\$