1.先进后出,分top和bottom
2.栈的应用:子程序的调用,递归调用,表达式的转换与求职,二叉树的遍历,图形的深度优先搜索
数组模拟栈:注意top=-1
package guigu;
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(4);
String key = “”;
boolean loop = true;
Scanner scanner = 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 = scanner.next();
switch(key){
case"show":
stack.list();
break;
case"push":
System.out.println(“请输入一个数”);
stack.push(scanner.nextInt());
break;
case"pop":
try {
System.out.println(stack.pop());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case"exit":
scanner.close();
loop = false;
break;
}
}
System.out.println("程序退出");
}
}
class ArrayStack{
private int maxSize;//栈的大小
private int[] stack;//数组模拟栈,数据放在该数组
private int top = -1;//栈底
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
//栈满
public boolean isFull(){
return top == maxSize - 1;
}
//栈空
public boolean isEmpty(){
return top == - 1;
}
//入栈 push
public void push(int value){
//是否满了
if(isFull()){
System.out.println("栈已满无法push");
return;
}
top++;
stack[top] = value;
}
//出栈 pop
public int pop(){
//是否为空
if(isEmpty()){
throw new RuntimeException("栈已空无法pop");
}
top--;
return stack[top+1];
}
//显示栈的情况,注意从栈顶显示情况
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]);
}
}
}