package com.example.sgg.data.stack;
import java.util.Scanner;
/**
* 数组模拟栈示例
* Created by 奔跑的蜗牛 on 2021/7/18 0018.
* 每天学习一点点,每天进步一点点
* <p>
* 栈的介绍:
* 1.栈的英文为stack;
* 2.先入后出(FILO);
* 3.栈是限制线性表中元素的插入(push)和删除(pop)都只能在线性表的同一端进行的特殊线性表。
* 允许插入和删除的一端称为栈顶,另一端为栈底;
* <p>
* 栈的应用场景:
* 1.子程序的调用:在跳往子程序前,会将下个指令的地址存到堆栈中,知道子程序执行完后
* 再将地址取出,以回到原来的程序中;
* 2.处理递归调用:和子程序的调用类似,只是除了存储下一个指令地址外,也将参数、区域变量
* 等数据存入堆栈中;
* 3.表达式的转换【中缀表达式转后缀表达式】与求值【实际解决】(PS:计算器公式的计算);
* 4.二叉树的遍历;
* 5.图形的深度优先【depth-first】算法
*/
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("s(show)表示遍历显示栈;");
System.out.println("a(push)表示压入数据到栈;");
System.out.println("p(pop)表示从栈中取出数据;");
System.out.println("e(exit)表示退出程序;");
System.out.println("请输入指令:");
key = scanner.next();
switch (key) {
case "s":
stack.list();
break;
case "a":
System.out.println("请输入要压入栈的数据:");
int value = scanner.nextInt();
stack.push(value);
break;
case "p":
try {
int pop = stack.pop();
System.out.printf("出栈的数据为:%d\n", pop);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "e":
loop = false;
break;
default:
break;
}
}
System.out.println("退出程序!");
}
}
//用数组模拟栈
class ArrayStack {
private int maxSize;
private int[] stack;
private int top = -1;//表示栈顶,初始值为-1
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[this.maxSize];
}
public boolean isFull() {
return top == this.maxSize - 1;
}
public boolean isEmpty() {
return top == -1;
}
/**
* 压栈
*
* @param value 数据
*/
public void push(int value) {
if (isFull()) {
System.out.println("栈满,无法加入数据");
return;
}
top++;
stack[top] = value;
}
/**
* 出栈
*/
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,无法取出数据");
}
int value = stack[top];
top--;
return value;
}
/**
* 遍历栈,需要从栈顶显示数据
*/
public void list() {
if (isEmpty()) {
System.out.println("栈空,没有数据~");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d] = %d\n", i, stack[i]);
}
}
}
数据结构-数组模拟栈
最新推荐文章于 2022-12-05 20:41:57 发布