/**
* 实现思路:
* 1. 提前创建一个数栈和一个符号栈,分别存储数字和计算符号
* 2. 遍历计算表达式 创建一个变量存储每次遍历得到的值
* 3. 如果遍历得到的是数字,直接入数栈
* 4. 如果得到的是符号,和符号栈里的栈顶比较,如果是<=的关系
* 取出符号栈的栈顶,用一个变量存储,再取出数栈里2个数字
* 计算出结果用一个变量存储,并将结果入数栈;如果是>的关系,直接入符号栈
* 5. 当表达式扫描完毕,按照就顺序的从数栈和符号栈中取出相应的数字和符号计算,每次将结果入数栈
* 6. 最后当符号栈空的时候计算完毕,返回数栈的结果即可
*/
public class test14 {
public static void main(String[] args) {
String expression = "7*2*2-5+1-5+3-4";
ArrayStack numStack = new ArrayStack(10);
ArrayStack operStack = new ArrayStack(10);
int num1 = 0; // 用于计算
int num2 = 0; // 用于计算
int oper = 0; // 用于计算,取出的运算符
int res = 0; // 运算结果保存
String keepNum = "" ; // 用于拼接多位数
int index = 0; // 用于扫描
char ch = ' '; // 表达式需要扫描,这里用来存储扫描的值
while(true){
ch = expression.substring(index,index + 1).charAt(0);
if(operStack.isOper(ch)){ // 判断是否为运算符
if(!operStack.isEmpty()){
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 {
// 数字是多位的情况,拼接数字,需要建立变量存储,知道下一位是符号,此时将数字入符号栈
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 = "";
}
}
}
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);
}
int res2 = numStack.pop();
System.out.printf("表达式 %s = %d", expression, res2);
}
}
class ArrayStack{
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack(int maxSize){
this.maxSize = maxSize;
stack = new int[maxSize];
}
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 boolean isOper(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
public int priority(int oper){
if(oper == '*' || oper == '/'){
return 1;
}else if(oper == '+' || oper == '-'){
return 0;
}else {
return -1;
}
}
public int cal(int num1,int num2,int oper){
int res = 0;
switch(oper){
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
default:
System.out.println("无");
break;
}
return res;
}
}
网友评论