1.データ構造とアルゴリズム:
ステップ1)データスタック要素を定義します。
private int maxSize; //栈容量
private int[] stack; //栈数组
private int top = -1; //栈底
ステップ2)要素を初期化します。
public ArrayStack(int maxSize){
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
ステップ3)データスタックがいっぱいの状態:
public boolean isFull(){
return top == maxSize-1;
}
ステップ4)データスタックが空の状態:
public boolean isEmpty(){
return top == -1;
}
ステップ5)データの保存方法:
public void push(int value){
if(isFull()){
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
ステップ6)データの抽出方法:
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空");
}
int value = stack[top];
top--;
return value;
}
ステップ7)データをトラバースする方法:
public void list(){
if(isEmpty()){
System.out.println("栈空");
}
for (int i=top; i>=0; i--){
System.out.printf("stack[%d]=%d\n",i, stack[i]);
}
}
ステップ8)主な方法:
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(4);
String key = "";
boolean loop = true;
Scanner sc = new Scanner(System.in);
while (loop){
System.out.println("show: 出栈");
System.out.println("exit: 退出");
System.out.println("push: 添加");
System.out.println("pop: 取出");
System.out.println("请输入");
key = sc.next();
switch (key){
case "show" :
stack.list();
break;
case "push" :
System.out.println("请输入一个数");
int value = sc.nextInt();
stack.push(value);
break;
case "pop" :
try {
int res = stack.pop();
System.out.printf("出栈的数据是:%d\n", res);
} catch (Exception e) {
System.out.printf(e.getMessage());
}
break;
case "exit" :
sc.close();
loop = false;
break;
}
}
System.out.println("程序退出");
}
• 2020年9月8日にChiKong_Tamによって書かれた