Last active
January 10, 2021 21:18
-
-
Save denkspuren/7bd76db97a54fc38e0754a9363390f2f to your computer and use it in GitHub Desktop.
Beispielhafte Stack-Implementierung in Java
This file contains hidden or 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
// Zur Erläuterung mein Video auf YouTube: https://youtu.be/RyrmcXY8oEw | |
interface Stackable { | |
boolean isEmpty(); | |
default int top() { throw new UnsupportedOperationException(); } | |
default Stackable pop() { throw new UnsupportedOperationException(); } | |
Stackable push(int element); | |
} | |
class StackWithElements implements Stackable { | |
private int element; | |
private Stackable previous; | |
static Stackable of(int... elements) { | |
Stackable s = new EmptyStack(); | |
for (int element : elements) { | |
s = s.push(element); | |
} | |
return s; | |
} | |
StackWithElements(Stackable previous, int element) { | |
assert Objects.nonNull(previous); | |
this.previous = previous; | |
this.element = element; | |
} | |
public boolean isEmpty() { return false; } | |
public Stackable push(int element) { | |
return new StackWithElements(this, element); | |
} | |
public int top() { return element; } | |
public Stackable pop() { return previous; } | |
@Override | |
public String toString() { | |
return pop() + " <- " + top(); | |
} | |
} | |
class EmptyStack implements Stackable { | |
public boolean isEmpty() { return true; } | |
public Stackable push(int element) { | |
return new StackWithElements(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