基本情報技術者試験 平成14年度・春期・午後 問8 ソースプログラム
import java.util.EmptyStackException;
public class IntStack {
private static final int INITIAL_CAPACITY = 10;
private static final int INCREMENT = 5;
private int capacity = INITIAL_CAPACITY;
private int[] content;
private int n_elements = 0;
public IntStack() { content = new int[capacity]; }
public boolean empty() { return n_elements == 0; }
public void push(int value) {
if (n_elements == content.length) {
// 配列を拡張する
int[] newContent = new int[capacity + INCREMENT];
for (int i = 0; i < capacity; i++) {
newContent[i] = content[i];
}
capacity += INCREMENT;
content = newContent;
}
content[n_elements++] = value;
}
public int peek() throws EmptyStackException {
if (n_elements > 0) {
return content[n_elements-1];
}
throw new EmptyStackException();
}
public int pop() throws EmptyStackException {
int value = peek();
n_elements--;
return value;
}
}
import java.io.*;
public class TestIntStack {
public static void main(String[] args) {
IntStack stack = new IntStack();
// 標準入力ストリームから読み込むためのReaderオブジェクトを生成する
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("=> ");
try {
String input = in.readLine(); // 標準入力から 1 行分読み込む
if (input.equals("")) break;
int n = Integer.parseInt(input);
stack.push(n);
} catch (Exception e) {
e.printStackTrace();
}
}
while (!stack.empty()) {
System.out.println(stack.pop());
}
System.out.println("--- bottom of Stack ---");
}
}