栈
栈的介绍
- 栈的英文为(stack)
- 栈是一个先入后出的有序列表
- 栈是限制线性表中元素的插入和删除只能在线性表的同一段进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶,另一端为固定的一端,称为栈底。
- 根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除。
栈的应用场景
- 子程序的调用:在跳往子程序前,会先将下一个指令的地址存到堆栈中,直到子程序执行完后再将地址取出,以回到原来的程序中。
- 处理递归调用:和子程序的调用类似,只是除了储存下一个指令的地址外,也将参数、区域变量等数据存入堆栈中。
- 表达式的转换【中缀表达式转后缀表达式】与求值(实际解决)。
- 二叉树的遍历。
- 图形的深度优先(depth-first)搜索法。
数组模拟栈
代码演示:
package com.lango.stack;
import java.util.Scanner;
/**
* @author Lango
* @version 1.0
*/
public class ArrayStackDemo {
public static void main(String[] args) {
// 测试
// 创建一个 ArrayStack
ArrayStack arrayStack = 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":
arrayStack.list();
break;
case "push":
System.out.println("请输入一个数:");
int value = scanner.nextInt();
arrayStack.push(value);
break;
case "pop":
try{
int res = arrayStack.pop();
System.out.printf("出栈的数据是%d\n",res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case "exit":
scanner.close();
loop = false;
break;
}
}
System.out.println("程序退出~");
}
}
// 定义一个 ArrayStack 表示栈
class ArrayStack {
private int maxSize; // 栈的大小
private int[] stack; // 数组,数组模拟栈,数据就放在该数组
private int top = -1; // top 表示栈顶,初始化为 -1
// 构造器
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
// 栈满
public boolean isFull() {
return top == maxSize - 1;
}
// 栈空
public boolean isEmpty() {
return top == -1;
}
// 入栈
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]);
}
}
}
链表模拟栈
代码演示:
package com.lango.stack;
/**
* @author Lango
* @version 1.0
*/
public class ArrayLinkedStackDemo {
public static void main(String[] args) {
// 测试
// 创建节点
ArrayLinked linked1 = new ArrayLinked(2);
ArrayLinked linked2 = new ArrayLinked(5);
ArrayLinked linked3 = new ArrayLinked(8);
ArrayLinked linked4 = new ArrayLinked(10);
ArrayLinked linked5 = new ArrayLinked(12);
ArrayLinked linked6 = new ArrayLinked(52);
ArrayLinkedStack arrayLinkedStack = new ArrayLinkedStack();
arrayLinkedStack.setMaxSize(5);
arrayLinkedStack.push(linked1);
arrayLinkedStack.push(linked2);
arrayLinkedStack.push(linked3);
arrayLinkedStack.push(linked4);
arrayLinkedStack.push(linked5);
arrayLinkedStack.list();
arrayLinkedStack.pop();
arrayLinkedStack.pop();
arrayLinkedStack.pop();
arrayLinkedStack.pop();
arrayLinkedStack.pop();
arrayLinkedStack.list();
arrayLinkedStack.push(linked1);
arrayLinkedStack.list();
}
}
class ArrayLinkedStack {
private ArrayLinked head = new ArrayLinked(-1);
private int maxSize; // 栈的大小
public ArrayLinked getHead() {
return head;
}
public void setHead(ArrayLinked head) {
this.head = head;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
public int getLength(ArrayLinked head) {
if (head.next == null) {
return 0;
}
int length = 0;
ArrayLinked temp = head.next;
while (temp != null) {
length++;
temp = temp.next;
}
return length;
}
// 栈满
public boolean isFull() {
return getLength(head) == maxSize;
}
// 栈空
public boolean isEmpty() {
return getLength(head) == 0;
}
// 入栈
public void push(ArrayLinked newHead) {
if (isFull()) {
System.out.println("栈满");
return;
}
ArrayLinked temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = newHead;
}
// 出栈
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
ArrayLinked temp = head;
ArrayLinked cur = temp.next;
while (true) {
if (cur.next == null) {
temp.next = null;
break;
}
temp = temp.next;
cur = cur.next;
}
System.out.printf("出栈stack = %d\n",cur.no);
return cur.no;
}
// 遍历栈
public void list() {
if (isEmpty()) {
System.out.println("栈空,没有数据");
return;
}
ArrayLinked temp = head.next;
while (temp != null) {
System.out.printf("stack = %d",temp.no);
temp = temp.next;
}
}
}
class ArrayLinked {
public int no;
public ArrayLinked next;
public ArrayLinked(int no) {
this.no = no;
}
@Override
public String toString() {
return "ArrayLinked{" +
"no=" + no +
'}';
}
}
栈实现综合计算器(中缀表达式)
使用栈完成表达式的计算思路:
- 通过一个 index 值(索引),来遍历我们的表达式。
- 如果我们发现是一个数字,就直接入数栈
- 如果我们发现是一个符号,就分如下情况:
- 如果发现当前的符号栈为空,就直接入栈
- 如果符号栈有操作符,就进行比较,如果当前操作符的优先级小于或者等于栈中的操作符,就需要从数栈中 pop 出两个数,再从符号栈中 pop 出一个符号,进行运算,将得到的结果入数栈,然后将当前的操作符入符号栈;如果当前的操作符优先级大于栈中的操作符,就直接入符号栈。
- 当表达式扫描完毕,就顺序的从数栈和符号栈中 pop 出相应的数和符号,并运行。
- 最后在数栈中只有一个数字,就是表达式的结果。
代码演示:
package com.lango.stack;
/**
* @author Lango
* @version 1.0
*/
public class Calculator {
public static void main(String[] args) {
// 代码实现
String expression = "70+2*6-40";
// 创建两个栈。数栈,符号栈
ArrayStack2 numStack = new ArrayStack2(10);
ArrayStack2 operStack = new ArrayStack2(10);
// 定义需要的相关变量
int index = 0; // 用于扫描
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' '; // 将每次扫描得到的 char 保存到 ch
String keepNum = ""; // 用于拼接 多位数
// 开始 while 循环扫描
while (true) {
// 依次得到 expression 的每一个字符
ch = expression.substring(index, index + 1).charAt(0);
// 判断 ch 是什么,然后做相应的处理
if (operStack.isOper(ch)) {// 如果是运算符
// 判断当前符号栈是否为空
if (!operStack.isEmpty()) {
// 如果符号栈有操作符,就进行比较,如果当前操作符的优先级小于或者等于栈中的操作符,就需要从数栈中 pop 出两个数,
// 再从符号栈中 pop 出一个符号,进行运算,将得到的结果入数栈,然后将当前的操作符入符号栈
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
// 把运算的结果入数栈
numStack.push(res);
// 把当前操作符入符号栈
operStack.push(ch);
} else {
// 如果当前的操作符优先级大于栈中的操作符,就直接入符号栈。
operStack.push(ch);
}
} else {
// 如果为空,直接入符号栈
operStack.push(ch);
}
} else {
// 如果是数,则直接入数栈
// numStack.push(ch - 48); // ASCII 表
// 分析思路:
// 1. 当处理多位数时,不能发现是一个数就立刻入栈,因为他可能是多位数
// 2. 在处理数时,需要向 expression 表达式的 index 后再后看一位,如果是数就继续扫描,如果是符号就入栈
// 3. 因此我们要定义一个变量 字符串,用于拼接
// 处理多位数
keepNum += ch;
// 如果 ch 已经是最后一位,就直接入栈
if (index == expression.length() - 1) {
numStack.push(Integer.parseInt(keepNum));
} else {
// 判断下一个字符是不是数字,如果是数字,则继续扫描,如果是运算符,则入栈
// 注意是看后一位,不是 index++
if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
// 后一位是运算符则入栈
numStack.push(Integer.parseInt(keepNum));
// 重要的!!!!,清空 keepNum
keepNum = "";
}
}
}
// 让 index + 1 并判断是否扫描到最后
index++;
if (index >= expression.length()) {
break;
}
}
// 当表达式扫描完毕,就顺序的从数栈和符号栈中 pop 出相应的数和符号,并运行。
while (true) {
// 最后在数栈中只有一个数字,就是表达式的结果。
if (operStack.isEmpty()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);// 入栈
}
System.out.printf("表达式%s = %d", expression, numStack.pop());
}
}
// 定义一个 ArrayStack2 表示栈
class ArrayStack2 {
private int maxSize; // 栈的大小
private int[] stack; // 数组,数组模拟栈,数据就放在该数组
private int top = -1; // top 表示栈顶,初始化为 -1
// 构造器
public ArrayStack2(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
// 返回当前栈订的值,但不是真正的 pop
public int peek() {
return stack[top];
}
// 栈满
public boolean isFull() {
return top == maxSize - 1;
}
// 栈空
public boolean isEmpty() {
return top == -1;
}
// 入栈
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]);
}
}
// 返回运算符的优先级,优先级是程序员来确定的,优先级使用数字表示
// 数字越大,优先级越高
public int priority(int oper) {
if (oper == '*' || oper == '/') {
return 1;
} else if (oper == '+' || oper == '-') {
return 0;
} else {
return -1; // 假定目前只有+,-,*,/
}
}
// 判断是不是一个运算符
public boolean isOper(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
// 计算方法
public int cal(int num1, int num2, int oper) {
int res = 0; // res 用于存放计算的结果
switch (oper) {
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
}