栈的应用场景
计算表达式:
7 * 2 * 2 + 5 + 3 * 2 - 3 / 2
栈的介绍
- 栈的英文 stack
- 栈是一个先入后出的有序列表
- 栈限制线性表只能在一端进行插入和删除,而允许插入和删除的这一端称为栈顶(top),另一端称为栈底(bottom)。
- 先进栈的元素在栈底,后进入的元素在栈顶。
栈的实现思路
- 因为栈也是一个列表,所以我们使用数组来模拟栈。
- 定义一个变量为 top,表示栈顶,初始化为 -1\
- 判断栈空
return top == -1;
- 判断栈满
return top == maxSize - 1;
- 入栈
top++; stack[top] = n;
- 出栈
temp = stack[top]; top--;
代码实现
class ArrayStack {
private int[] arr;
private int maxSize;
private int top = -1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
}
//判断栈满
public boolean isFull() {
return top == maxSize - 1;
}
//判断栈空
public boolean isEmpty() {
return top == -1;
}
//入栈
public void push(int num) {
if(isFull()) {
System.out.println("栈满,不能入栈");
return;
}
top++;
arr[top] = num;
}
//出栈
public int pop() {
if(isEmpty()){
throw new RuntimeException("栈空,不能出栈")
}
int value = arr[top];
top--;
return value;
}
//遍历栈
//遍历时需要从栈顶开始显示数据
public void list() {
for(int i = top; i >= 0; i--) {
System.out.println(arr[i]);
}
}
}
测试
public class ArrayStackDemo {
public static void main(String[] args) {
//测试 ArrayStack 是否正确
//先创建一个ArrayStack
ArrayStack stack = new ArrayStack(4);
String key = "";
boolean loop = true;
Scanner in = 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 = in.next();
switch(key) {
case "show":
stack.list();
break;
case "exit":
loop = false;
break;
case "push":
System.out.println("请输入一个整数");
int num = in.nextInt();
stack.push(num);
break;
case "pop":
try{
System.out.println(stack.pop());
} catch(Exception e){
e.printStackTrace();
}
default:
break;
}
}
}
}
计算器实现(计算中缀表达式)
设计思路:
- 建立两个栈:数栈和符号栈
- 遍历表达式,如果是数字,就直接进栈,如果是一个符号,就分如下两种情况:
- 如果符号栈为空,就直接入栈
- 如果符号栈栈顶元素优先级大于等于该元素优先级,栈顶元素出栈,数栈中出栈两个元素,做相应运算后,运算结果存到数栈中。重复此操作直到符号栈为空,或符号栈栈顶元素优先级小于该元素优先级。 - 遍历结束后,符号栈出栈一个元素,数栈出栈两个元素,做相应运算后结果存到数栈中。直到符号栈为空(或数栈中只有一个元素)为止。
代码:
import java.util.HashMap;
import java.util.Stack;
public class Calculator {
public static void main(String[] args) {
String expression = "7 * 2 * 2 - 5 + 1 - 5 + 3 - 4";
System.out.println(calculate(expression));
}
//表达式中只有数字、+、-、*、/
public static int calculate(String expression) {
Stack<Integer> numStack = new Stack<>();
Stack<Character> operationStack = new Stack<>();
StringBuffer sb = new StringBuffer();
HashMap<Character, Integer> Priority = new HashMap<>();
Priority.put('+', 1);
Priority.put('-', 1);
Priority.put('*', 2);
Priority.put('/', 2);
for(int i = 0; i < expression.length(); i++) {
char cur = expression.charAt(i);
if(cur == '+' || cur == '-' || cur == '*' || cur == '/') {
if(sb.length() > 0) {
numStack.push(Integer.parseInt(sb.toString().trim()));
sb.delete(0, sb.length());
}
while(!operationStack.empty() && Priority.get(cur) <= Priority.get(operationStack.peek()) ) {
int num1 = numStack.pop();
int num2 = numStack.pop();
char operation = operationStack.pop();
numStack.push(operate(num1, num2, operation));
}
operationStack.push(cur);
} else {
sb.append(cur);
}
}
if(sb.length() > 0)
numStack.push(Integer.parseInt(sb.toString().trim()));
while(!operationStack.empty()) {
int num1 = numStack.pop();
int num2 = numStack.pop();
char operation = operationStack.pop();
numStack.push(operate(num1, num2, operation));
}
return numStack.peek();
}
public static int operate(int a, int b, char operation) {
int result = 0;
switch(operation) {
case '+':
result = b + a;
break;
case '-':
result = b - a;
break;
case '*':
result = b * a;
break;
case '/':
result = b / a;
break;
}
return result;
}
}