Created
January 3, 2023 11:37
-
-
Save jordancodurance/6b5ef000864fe8a1d19729a397d7985e to your computer and use it in GitHub Desktop.
Special case null stack solution for https://www.codurance.com/katalyst/stack
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
interface Stack { | |
static Stack create(int size) { | |
if (size < 0) throw new IllegalStackSizeException(); | |
if (size == 0) return new NullStack(); | |
return new BoundedStack(size); | |
} | |
void push(int element); | |
boolean isEmpty(); | |
// Other operations... | |
} | |
class NullStack implements Stack { | |
@Override public void push(int element) { | |
throw new StackOverFlowException(); // 0 stack always overflows | |
} | |
@Override public boolean isEmpty() { | |
return true; // 0 stack is always empty | |
} | |
} | |
class BoundedStack implements Stack { | |
@Override public void push(int element) { | |
// push code | |
} | |
@Override public boolean isEmpty() { | |
// empty check code | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the special case of a null stack, if you are using a language which supports polymorphism, consider creating a base abstract
Stack
, aBoundedStack
with your current implementation, and aNullStack
with only the code required for the 0 case. Then provide a way to construct either derivate of the stack based on the size provided.