65 lines
1.2 KiB
Java
65 lines
1.2 KiB
Java
|
package VL13.Aufgabe01;
|
||
|
|
||
|
/**
|
||
|
* A integer stack.
|
||
|
*/
|
||
|
public class IntegerStack {
|
||
|
StackItem start;
|
||
|
|
||
|
private class StackItem {
|
||
|
int value;
|
||
|
StackItem next;
|
||
|
StackItem prev;
|
||
|
|
||
|
StackItem(int value) {
|
||
|
this.value = value;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Method to push a value to the stack.
|
||
|
*
|
||
|
* @param value The value to store on the stack.
|
||
|
*/
|
||
|
public void push(int value) {
|
||
|
if (start == null) {
|
||
|
start = new StackItem(value);
|
||
|
} else {
|
||
|
StackItem 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(value);
|
||
|
item.next.prev = item;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Method to pop a value from the stack.
|
||
|
*
|
||
|
* @return The value from stack.
|
||
|
*/
|
||
|
public int pop() {
|
||
|
StackItem 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 && item == start) {
|
||
|
start = null;
|
||
|
} else {
|
||
|
item.prev.next = null;
|
||
|
}
|
||
|
|
||
|
// return the value of the last item of the stack.
|
||
|
return item.value;
|
||
|
}
|
||
|
}
|