思路
1.使用一个数字栈一个符号栈;
2.通过一个index值遍历表达式;
3.如发现是数字,就直接放入数字栈;
4.如发现是符号,进行优先级比较,如果当前的操作符的优先级小于或者等于栈顶的操作符,就需要从数字栈中pop两个数字,从符号栈中pop一个符号进行计算,将得到的结果放入数字栈,将当前的符号放入符号栈,如果操作符优先级大于栈顶的操作符,则直接入符号栈;
5.当表达式扫描完毕,就顺序的从数栈和符号中pop出相应的数字和符号进行运算
6.最后数字栈只有一个数字,即为所求结果
在循环里面考虑多位数
代码实现
栈的结构
package com.company;
public class ArrayStack {
private int maxSize;//栈的大小
private int[] stack;//数组模拟栈
private int top = -1;//top表示栈顶,初始化为-1
public ArrayStack(int maxSize){
this.maxSize =maxSize;
stack = new int[maxSize];
}
public boolean isFull(){
return top == maxSize-1;
}
public boolean isEmpty(){
return top==-1;
}
//入栈
public void push(int value){
if(isFull()){
System.out.println("the stack is filled");
return;
}
top++;
stack[top]=value;
}
//出栈
public int pop(){
if(isEmpty()){
// System.out.println("the stack is empty");
//抛出异常
throw new RuntimeException("the stack is empty!");
}
int value = stack[top];
top--;
return value;
}
public void list(){
if(isEmpty()){
System.out.println("the stack is empty!");
return;
}
for(int i=top;i>=0;i--){
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
//确定优先级
public int priority(int ope){
if(ope=='*'||ope=='/'){
return 1;
}else if(ope=='+'||ope=='-'){
return 0;
}else {
return -1;
}
}
public int peek(){
return stack[top];
}
//判断是否为运算符
public boolean isOpe(char value){
return value=='+'||value=='-'||value =='*'||value =='/';
}
//计算方法
public int cal(int n1,int n2,int ope){
int res=0;//存放计算结果
switch (ope){
case '+':
res= n1+n2;
break;
case '-':
res=n2-n1;
break;
case '*':
res = n1*n2;
break;
case '/':
res = n2/n1;
break;
}
return res;
}
}
计算逻辑
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
String expression = "3+2*6-2";
ArrayStack numStack = new ArrayStack(10);
ArrayStack opeStack = new ArrayStack(10);
int index = 0;
int n1 = 0;
int n2 = 0;
int ope = 0;
int res = 0;
char ch = ' ';
String numKeeper = "";//多位数保存器
//扫描表达式
while(true){
ch = expression.substring(index,index+1).charAt(0);
if(opeStack.isOpe(ch)) {
if (!opeStack.isEmpty()) {
if (opeStack.priority(ch) <= opeStack.priority(opeStack.peek())) {
n1 = numStack.pop();
n2 = numStack.pop();
ope = opeStack.pop();
res = numStack.cal(n1, n2, ope);
numStack.push(res);
opeStack.push(ch);
} else {
opeStack.push(ch);
}
} else {
opeStack.push(ch);
}
}else {
numKeeper += ch;
if(index == expression.length()-1){
numStack.push(Integer.parseInt(numKeeper));
}else {
if(opeStack.isOpe(expression.substring(index+1,index+2).charAt(0))){
numStack.push(Integer.parseInt(numKeeper));
numKeeper = "";
}
}
}
index++;
if(index>=expression.length()){
break;
}
}
while (true){
if(opeStack.isEmpty()){
break;
}
n1=numStack.pop();
n2=numStack.pop();
ope=opeStack.pop();
res = numStack.cal(n1,n2,ope);
numStack.push(res);
}
System.out.printf("表达式%s = %d",expression,numStack.pop());
}
}