1. Data structure and algorithm:
Step 1) Define data stack elements:
private int maxSize; //栈容量
private int[] stack; //栈数组
private int top = -1; //栈底
Step 2) Initialize elements:
public ArrayStack(int maxSize){
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
Step 3) Data stack full condition:
public boolean isFull(){
return top == maxSize-1;
}
Step 4) The data stack is empty condition:
public boolean isEmpty(){
return top == -1;
}
Step 5) Method of saving data:
public void push(int value){
if(isFull()){
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
Step 6) Method of extracting data:
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空");
}
int value = stack[top];
top--;
return value;
}
Step 7) Method of traversing data:
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]);
}
}
Step 8) main method:
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("程序退出");
}
• Written by ChiKong_Tam on September 8, 2020