// H. Moessenboeck: Sprechen Sie Java? -- Kapitel 18, Aufgabe 3
// "Paket util"
/** A stack of integers.
This class implements a LIFO stack of a fixed size.
The operations are {@link Stack#push} and {@link Stack#pop} which set
{@link Stack#overflow} and {@link Stack#underflow} if the stack is full or empty.
@author H.Moessenboeck
@version 1.0
*/
package util;
public class Stack {
protected int s[]; // the stack
protected int length; // number of elements in s
/** Stack overflow.
This flag is set to true if the stack became full during a push operation. */
public boolean overflow = false;
/** Stack underflow.
This flag is set to true if a pop operation was applied to an empty stack. */
public boolean underflow = false;
/** Creates a stack with size elements.
Only size-1 elements can be used. */
public Stack(int size) {
s = new int[size];
length = 0;
}
/** Adds an element.
The element x is added to the end of the stack. If the stack
is full, nothing is added and {@link Stack#overflow} is set to true.
@param x The element to be added to the stack. */
public void push(int x) {
overflow = length >= s.length;
if (!overflow) s[length++] = x;
}
/** Removes an element.
An element is removed and returned from the end of the stack. If the
stack is empty, -1 is returned and {@link Stack#underflow} is set to true.
@return The last element from the stack. */
public int pop() {
underflow = length == 0;
if (!underflow) return s[--length]; else return -1;
}
}