package com.stack;
/*
* 基本介绍:
* 1、栈的英文是stack
* 2、栈是一个先进后出(FILO-First In Last Out)的有序列表
* 3、栈是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表
* 允许插入和删除的一端,为变化的一端,称为栈顶,另一端为固定的一端,称为栈底
* 4、根据栈的定义可知,最先放入栈中的元素在栈底,最后放入的元素在栈顶,而删除元素则刚好相反,
* 最后放入的元素最先删除,最先放入的元素最后删除
*
* 栈的应用场景:
* 1、子程序的调用:在跳往子程序前,会先将下一个指令的地址存储到对战中,直到子程序执行完成后再将地址取出
* 以回到原来的程序中
* 2、处理递归调用:和子程序的调用类似,知识除了存储下一个指令的地址外,也将参数、区域变量等数据存入堆栈中
* 3、表达式的转换(中缀表达式转后缀表达式)与求值(实际解决)
* 4、二叉树的遍历
* 5、图形的深度优先(depth-first)搜索法
*
* 实现栈思路分析
* 1、使用数组模拟栈
* 2、定义一个top来表示栈顶,初始化为-1
* 3、入栈的操作:当有数据加入到栈时,top++,stack[top]=data;
* 4、出栈的操作:int value = stack[top];top--;
*
*/
//定义一个ArrayStack表示栈
class ArrayStack
{
private int maxSize;//栈的大小
private int[] stack;//数组,数组模拟栈,数据就放在数组里
private int top=-1;//top表示栈顶,初始化值为-1;
//构造器
public ArrayStack(int maxSize)
{
this.maxSize=maxSize;
this.stack=new int[this.maxSize];
}
//栈满
public boolean isFull()
{
return this.top==this.maxSize-1;
}
//栈空
public boolean isEmpty()
{
return this.top==-1;
}
//入栈 push
public void push(int value)
{
//先判断栈是否满
if(this.isFull())
{
System.out.println("栈满");
return;
}
this.top++;
this.stack[this.top]=value;
}
//出栈 pop,将栈顶的数据返回
public int pop()
{
//先判断是否为空
if(this.isEmpty())
{
throw new RuntimeException("栈空,没有数据");
}
int value=this.stack[this.top];
this.top--;
return value;
}
//显示栈的情况,即遍历栈,遍历栈时需要从栈顶开始显示数据
public void list()
{
if(this.isEmpty())
{
System.out.println("栈空,没有数据");
return ;
}
for(int i=this.top;i>=0;i--)
{
System.out.printf("this.stack[%d]=%d\n", i,this.stack[i]);
}
}
}
public class ArrayStackDemo {
public static void main(String[] args) {
// 测试一下ArrayStack类是否正确
// 先创建一个ArrayStack的一个对象,表示一个栈
ArrayStack as=new ArrayStack(4);
as.push(10);
as.push(20);
as.push(30);
as.push(40);
as.push(50);
as.list();
System.out.println("检测pop方法的正确性");
int value=as.pop();
System.out.printf("出栈的数据为%d \n", value);
as.list();
}
}
运行结果为:
栈满
this.stack[3]=40
this.stack[2]=30
this.stack[1]=20
this.stack[0]=10
检测pop方法的正确性
出栈的数据为40
this.stack[2]=30
this.stack[1]=20
this.stack[0]=10