-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Pap Lőrinc
committed
Feb 10, 2016
1 parent
0840091
commit c519e63
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package Ch03_StacksAndQueues | ||
|
||
import Ch03_StacksAndQueues.utils.Stack | ||
|
||
/** Create stack with O(1) minimum */ | ||
class MinStack<T> extends Stack<T> { | ||
private final mins = new Stack<T>() | ||
|
||
@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() } | ||
} |
28 changes: 28 additions & 0 deletions
28
src/test/groovy/Ch03_StacksAndQueues/_3_2_MinStackTest.groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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..<source.size()].min() | ||
assert stack.pop() == value | ||
} | ||
stack.empty | ||
} | ||
/*@formatter:on*/ | ||
} |