CS 1723 -- The Simplest Possible Stack of Integers
(Not at all Object-Oriented)
Here is the simplest straight-line program I could write
that creates a stack of ints.
This code stands by itself, without
any other classes. The functions of the IntStack
class are just incorporated directly into the main
method. (Part of the reason this is not a good implementation is
that the code for the stack is scattered in the main
method.)
// SimpleStack: the simplest possible stack of ints
public class SimpleStack {
public static void main(String[] args) {
int[] stackArray = new int[6]; // the actual list
int top = 0; // current number of elements
// push ints onto the stack.
for (int i = 0; i < 10; i++) {
// here is the code for a push
if (top >= stackArray.length) { // double size
int[] tempArray = new int[stackArray.length * 2];
for(int k = 0; k < top; k++)
tempArray[k] = stackArray[k];
stackArray = tempArray;
}
stackArray[top++] = i*i;
}
// pop and print the stack
while (top != 0) {
System.out.print(stackArray[--top] + " ");
}
System.out.println("\nTh-th-th-th-that's-all-folks");
}
}
Sample run.
% java SimpleStack
81 64 49 36 25 16 9 4 1 0
Th-th-th-th-that's-all-folks
Revision date: 2001-09-06.
(Please use ISO
8601, the International Standard.)