CS 1723 -- Simple Stack of Integers
(Created From Scratch)
Here is a simple program that creates a stack of ints from
scratch without using any Java libraries.
// Stack: interface for a simple stack of ints
public interface Stack {
// pop: remove top element and return it
public int pop() throws StackUnderflowException;
// push: puch parameter onto stack
public void push(int x);
// empty: is stack empty?
public boolean empty();
// peek: return top element without popping
public int peek() throws StackUnderflowException;
}
// StackUnderflowException: exception created for IntStack class
public class StackUnderflowException extends Exception {
public StackUnderflowException() {
System.out.println("Stack Underflow");
}
}
// Stack: implementation for a simple stack of ints, using an array
public class IntStack {
// fields
private int[] stackArray; // the actual list
private int top; // current number of elements
private final int INITIAL_SIZE = 6; // initial maximum size
// IntStack: constructor
public IntStack () {
top = 0; // not needed (already done)
stackArray = new int[INITIAL_SIZE]; // allocate array
}
// pop: remove top element and return it
public int pop() throws StackUnderflowException {
if (top == 0) {
throw new StackUnderflowException();
}
else
return stackArray[--top];
}
// push: push parameter onto stack
public void push(int x) {
if (top >= stackArray.length)
doubleArray();
stackArray[top++] = x;
}
// empty: is stack empty?
public boolean empty() {
return top == 0;
}
// peek: return top element without popping
public int peek() throws StackUnderflowException {
if (top == 0) {
throw new StackUnderflowException();
}
else
return stackArray[top - 1];
}
// doubleArray: double the size of the array
private void doubleArray() {
int[] tempArray = new int[stackArray.length * 2];
for(int k = 0; k < top; k++)
tempArray[k] = stackArray[k];
stackArray = tempArray;
}
}
// StackMain: make use of the a simple stack of ints
public class StackMain {
public static void main(String[] args) {
// create two stacks
IntStack s = new IntStack();
IntStack t = new IntStack();
// push ints onto the stacks. Need wrappers
for (int i = 0; i < 10; i++) {
int j = i*i;
s.push(j); t.push(j);
}
// pop and print the first stack, using empty()
// method to terminate loop
while (!s.empty()) {
try {
System.out.print(s.pop() + " ");
} catch (StackUnderflowException suf) {
System.out.println("This should not print!");
}
}
System.out.println("\nEnd of the first stack");
// pop and print 2nd stack, using StackUnderflowkException
// to terminate loop
while (true) {
try {
System.out.print(t.pop() + " ");
} catch (StackUnderflowException suf) {
break;
}
}
System.out.println("\nTh-th-th-th-that's-all-folks");
}
}
Sample run.
% java StackMain
81 64 49 36 25 16 9 4 1 0
End of the first stack
81 64 49 36 25 16 9 4 1 0 Stack Underflow
Th-th-th-th-that's-all-folks
Revision date: 2001-09-06.
(Please use ISO
8601, the International Standard.)