diff --git a/src/main/groovy/Ch03_StacksAndQueues/_3_2_MinStack.groovy b/src/main/groovy/Ch03_StacksAndQueues/_3_2_MinStack.groovy new file mode 100644 index 0000000..c1d45ef --- /dev/null +++ b/src/main/groovy/Ch03_StacksAndQueues/_3_2_MinStack.groovy @@ -0,0 +1,18 @@ +package Ch03_StacksAndQueues + +import Ch03_StacksAndQueues.utils.Stack + +/** Create stack with O(1) minimum */ +class MinStack extends Stack { + private final mins = new Stack() + + @Override void push(T value) { + (mins.empty || (value <= peekMin())) && mins.push(value) /* equal elements have to be repeated */ + super.push(value) + } + @Override T pop() { + (peek() == peekMin()) && mins.pop() + super.pop() + } + T peekMin() { mins.peek() } +} \ No newline at end of file diff --git a/src/test/groovy/Ch03_StacksAndQueues/_3_2_MinStackTest.groovy b/src/test/groovy/Ch03_StacksAndQueues/_3_2_MinStackTest.groovy new file mode 100644 index 0000000..22de451 --- /dev/null +++ b/src/test/groovy/Ch03_StacksAndQueues/_3_2_MinStackTest.groovy @@ -0,0 +1,28 @@ +package Ch03_StacksAndQueues + +import spock.lang.Specification + +import static java.lang.Math.* + +class _3_2_MinStackTest extends Specification { + /*@formatter:off*/ + def 'minStack?'() { + given: def source = "$PI$E".toList() + + when: 'a new stack is empty' + def stack = new MinStack() + then: stack.empty + + when: 'consuming a stack yields the correct value and min' + source.reverseEach { + stack.push(it) + assert !stack.empty + } + then: source.eachWithIndex { value, i -> + assert stack.peekMin() == source[i..