利用栈实现算术表达式的求值
package com.my.datastructure;
import java.util.Stack;
/**
* @author zhe.sun
* @Description: 利用栈实现算术表达式的求值
* @date 2020/5/8 23:25
*/
public class StackTest {
public static void main(String[] args) {
System.out.println(convert("(3 + 4) * 5 - 6"));
System.out.println(calcPostExp(" 6 5 2 3 + 8 * + 3 + *"));
}
/**
* 建立一个栈S 。从左到右读表达式,如果读到操作数就将它压入栈S中,
* 如果读到n元运算符(即需要参数个数为n的运算符)则取出由栈顶向下的n项按操作符运算,
* 再将运算的结果代替原栈顶的n项,压入栈S中 。如果后缀表达式未读完,
* 则重复上面过程,最后输出栈顶的数值则为结束。
* @param postExp
* @return
*/
public static int calcPostExp(String postExp) {
Stack<Integer> integers = new Stack<>();
for(char c : postExp.trim().toCharArray()) {
if(isNumber(c)) {
integers.push(Integer.parseInt(c + ""));
}
if(isOperator(c)) {
int num = integers.pop();
int num2 = integers.pop();
integers.push(calculate2Numbers(num,num2,c));
}
}
return integers.pop();
}
/**
*
* @param num1
* @param num2
* @param operator
* @return
*/
public static Integer calculate2Numbers(int num1, int num2, char operator) {
switch(operator) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
}
return null;
}
/**
* 中缀表达式 --> 后缀表达式
*
*
* 建立符号栈
* 顺序扫描中序表达式
* a) 是数字, 直接输出
* b) 是运算符
* i : “(” 直接入栈
* ii : “)” 将符号栈中的元素依次出栈并输出, 直到 “(“, “(“只出栈, 不输出
* iii: 其他符号, 如果当前栈顶符号不是”(“ 并且 当前栈顶符号优先级大于等于该符号,
* 将符号栈中的元素依次出栈并输出, 否则 将当前符号入栈。
* 扫描完后, 将栈中剩余符号依次输出
* @param inExp
* @return
*/
public static String convert(String inExp) {
StringBuilder postExp = new StringBuilder(100);
Stack<Character> operator = new Stack<>();
for(char c : inExp.trim().toCharArray()) {
if(isNumber(c)) {
postExp.append(c);
}
if(isOperator(c)) {
if(c == '(') {operator.push(c);}
else if(c == ')') {
while(operator.size() != 0 && operator.peek() != '(') {
postExp.append(operator.pop());
}
//只出栈, 不输出
operator.pop();
}else {
while(operator.size() != 0 && operator.peek() != '(' && priority(operator.peek()) >= priority(c) ) {
postExp.append(operator.pop());
}
operator.push(c);
}
}
}
while (operator.size() != 0) {
postExp.append(operator.pop());
}
return postExp.toString();
}
public static boolean isNumber(char ch) {
if(ch >= '0' && ch <= '9') {
return true;
}
return false;
}
public static boolean isOperator(char ch) {
if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')') {
return true;
}
return false;
}
/**
* 运算符优先级比较
* @param charValue
* @return
*/
public static int priority(char charValue) {
switch (charValue) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
return 0;
}
}
代码如上,欢迎指正~

前序:根左右
中序:左根右
后序:左右根
参考:https://blog.csdn.net/u012507347/article/details/52245233
本文介绍了一种使用栈数据结构实现算术表达式求值的方法,包括中缀表达式转换为后缀表达式的过程及后缀表达式的计算算法。通过具体代码示例,展示了如何处理操作数和运算符,进行优先级比较,以及实现完整的计算流程。

被折叠的 条评论
为什么被折叠?



