思路解析
通过两个栈:数栈与符号栈解决中缀表达式的问题。具体思路如下(来源于韩顺平老师课件):
JAVA代码实战
基于上一篇博客通过数组模拟栈,增加更多的方法有助于我们解决中缀表达式的问题。具体栈的类构造如下:
class ArrayStack{
private int maxSize; //栈的大小
private int[] stack;
private int 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;
}
//返回栈顶的值,非pop操作
public int showTop(){
return stack[top];
}
//入栈 push
public void push(int value){
if(isFull()){
System.out.println("栈满,无法入栈");
return;
}
stack[++top] = value;
}
//出栈 pop
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空");
}
int value = stack[top--];
return value;
}
//遍历,遍历时需要从栈顶开始显式数据
public void show(){
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 value = 0;
switch (oper){
case '+':
value = num1 + num2;
break;
case '-':
value = num2 - num1;
break;
case '*':
value = num1 * num2;
break;
case '/':
value = num2 / num1;
default:
break;
}
return value;
}
}
根据思路解析,实现相应代码并进行测试。注意多位数的处理!
public class Calculator {
public static void main(String[] args) {
String expression = "10+2*3-3*12";
//创建两个栈,数栈与符号栈
ArrayStack numStack = new ArrayStack(10);
ArrayStack operStack = new ArrayStack(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){
ch = expression.substring(index,index+1).charAt(0);
if(operStack.isOper(ch)){
if(!operStack.isEmpty()){
if(operStack.priority(ch) <= operStack.priority(operStack.showTop())){
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 {
//需要判断是否为多位数
keepNum += ch;
if(index == expression.length()-1){
numStack.push(Integer.parseInt(keepNum));
}else{
if(operStack.isOper(expression.substring(index+1,index+2).charAt(0))){
numStack.push(Integer.parseInt(keepNum));
//清空keepNum
keepNum = "";
}
}
}
index++;
if(index >= expression.length()){
break;
}
}
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());
}
}