特点:先进后出,也就是比队列要更简单,用一个索引就ok了,栈的打印也是按照其特点来打印的。
package a;
import java.util.Scanner;
public class StaDemo {
public static void main(String[] args) {
Sta sta = new Sta(2);
String word ="";
boolean flag = true;
Scanner scanner = new Scanner(System.in);
while (flag) {
System.out.println("show show the data");
System.out.println("push add data");
System.out.println("pop get data");
System.out.println("exit return");
word = scanner.next();
switch (word) {
case "show":sta.show();
break;
case "push":
System.out.println("please put");
sta.push(scanner.nextInt());
break;
case "pop":
int pop = 0;
try {
pop = sta.pop();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("pop = " + pop);
break;
case "exit":scanner.close();
flag = false;
break;
default: break;
}
}
System.out.println("have exit");
}
}
class Sta{
int top;
int max;
int [] arr;
public Sta(int max) {
this.max = max;
arr = new int[max];
top = -1;
}
public boolean isFull() {
return (max-1)==top;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int val) {
if (isFull()) {
System.out.println("isFull");
return;
}
top++;//这是先找位置,然后赋值
arr[top]=val;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("isEmpty");
}
int res = arr[top];
top--;
return res;
}
public void show() {
if (isEmpty()) {
System.out.println("isEmpty");
return;
}
for (int i = top; i >=0 ; i--) {
System.out.println(arr[i]);
}
}
}