68 lines
1.3 KiB
Java
68 lines
1.3 KiB
Java
|
package VL13.Aufgabe01;
|
||
|
|
||
|
/**
|
||
|
* A generic stack.
|
||
|
*/
|
||
|
public class GenericStack<T> {
|
||
|
StackItem<T> start;
|
||
|
|
||
|
/**
|
||
|
* A stack item to store a single item on the stack.
|
||
|
*/
|
||
|
private class StackItem<E> {
|
||
|
E value;
|
||
|
StackItem<E> next;
|
||
|
StackItem<E> prev;
|
||
|
|
||
|
StackItem(E value) {
|
||
|
this.value = value;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Method to push a value to the stack.
|
||
|
*
|
||
|
* @param value The value to store on the stack.
|
||
|
*/
|
||
|
public void push(T value) {
|
||
|
if (start == null) {
|
||
|
start = new StackItem<T>(value);
|
||
|
} else {
|
||
|
StackItem<T> item = start;
|
||
|
|
||
|
// get the last item of the stack.
|
||
|
while (item.next != null) {
|
||
|
item = item.next;
|
||
|
}
|
||
|
|
||
|
// create a new stack item to store the value.
|
||
|
item.next = new StackItem<T>(value);
|
||
|
item.next.prev = item;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Method to pop a value from the stack.
|
||
|
*
|
||
|
* @return The value from stack.
|
||
|
*/
|
||
|
public T pop() {
|
||
|
StackItem<T> item = start;
|
||
|
|
||
|
// get the last item of the stack.
|
||
|
while (item.next != null) {
|
||
|
item = item.next;
|
||
|
}
|
||
|
|
||
|
// remove last item from stack.
|
||
|
if (item.prev == null) {
|
||
|
start = null;
|
||
|
} else {
|
||
|
item.prev.next = null;
|
||
|
}
|
||
|
|
||
|
// return the value of the last item of the stack.
|
||
|
return item.value;
|
||
|
}
|
||
|
}
|