Skip to content

Instantly share code, notes, and snippets.

@denkspuren
Last active January 10, 2021 21:17
Show Gist options
  • Save denkspuren/447a84a26538b066cddfbe4912373763 to your computer and use it in GitHub Desktop.
Save denkspuren/447a84a26538b066cddfbe4912373763 to your computer and use it in GitHub Desktop.
Eine (typ)generische Stack-Implementierung
// Zur Erläuterung mein Video auf YouTube: https://youtu.be/rSuE2vIUzzk
interface Stackable<T> {
boolean isEmpty();
default T top() { throw new UnsupportedOperationException(); }
default Stackable<T> pop() { throw new UnsupportedOperationException(); }
Stackable<T> push(T element);
}
class StackWithElements<T> implements Stackable<T> {
private T element;
private Stackable<T> previous;
@SafeVarargs static <T> Stackable<T> of(T... elements) {
Stackable<T> s = new EmptyStack<T>();
for (T element : elements) {
s = s.push(element);
}
return s;
}
StackWithElements(Stackable<T> previous, T element) {
assert Objects.nonNull(previous);
this.previous = previous;
this.element = element;
}
public boolean isEmpty() { return false; }
public Stackable<T> push(T element) {
return new StackWithElements<T>(this, element);
}
public T top() { return element; }
public Stackable<T> pop() { return previous; }
@Override
public String toString() {
return pop() + " <- " + top();
}
}
class EmptyStack<T> implements Stackable<T> {
public boolean isEmpty() { return true; }
public Stackable<T> push(T element) {
return new StackWithElements<T>(this, element);
}
@Override
public String toString() {
return "[ ]";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment