Java数据结构:栈(stack)
2020-07-06 本文已影响0人
Patarw
1.栈的基本介绍
- 栈是一个先入后出(FILO-First In Last Out)的有序列表。
- 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
- 根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除.
出栈(pop)和入栈(push)的概念(如图所示)
![](https://img.haomeiwen.com/i20809921/f53604559af04845.png)
![](https://img.haomeiwen.com/i20809921/0b3951214d7d9f31.png)
2.栈的一些应用场景
- 子程序的调用:在跳往子程序前,会先将下个指令的地址存到堆栈中,直到子程序执行完后再将地址取出,以回到原来的程序中。
- 处理递归调用:和子程序的调用类似,只是除了储存下一个指令的地址外,也将参数、区域变量等数据存入堆栈中。
- 表达式的转换[中缀表达式转后缀表达式]与求值(实际解决)。
- 二叉树的遍历。
- 图形的深度优先(depth一first)搜索法。
3.使用代码实现栈
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(10);
stack.push(1);
stack.push(5);
stack.push(6);
stack.pop();
stack.list();
}
}
//用ArrayStack来表示栈
class ArrayStack{
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[maxSize];
}
//判断是否栈满
public boolean isFull() {
return top == maxSize-1;
}
//判断是否栈空
public boolean isEmpty() {
return top == -1;
}
//入栈,push方法
public void push(int value) {
if(this.isFull()) {
System.out.println("栈满,无法入栈");
}
top++;
stack[top] = value;
}
//出栈,pop方法
public int pop() {
if(this.isEmpty()) {
throw new RuntimeException("栈空,无法出栈");
}
int value = stack[top];
top--;
return value;
}
//遍历栈,从栈顶开始
public void list() {
if(isEmpty()) {
System.out.println("栈空");
}
for(int i = top;i>=0;i--) {
System.out.println(stack[i]);
}
}