思路分析
利用栈这个数据结构先入后出的特点。利用两个栈一个数字栈,一个符号栈。实现计算。
1.遍历表达式的每个字符,如果是数字就入数栈。注意数字可能是多位数,所以在读数字是要合并一下连续的数字,知道下个符号出现。
2.读到的是符号时,先判断符号栈是否为空,如果为空就直接入符号栈。如果不为空则判断优先级,如果栈中大于当前,将栈中符号弹出,进行预算,再把当前符号入栈,如果当前大于栈中,直接入栈。
3.运算时,从数栈中出两个数,符号栈中出一个符号。运算,直到栈中仅剩一个数,符号栈为空。此时数栈中的数即为结果
代码:
package edu.xalead;
class ArrayStack1{
private int maxsize;
private int[]Stack;
private int top=-1;
public ArrayStack1(int maxsize){
this.maxsize=maxsize;
Stack=new int[maxsize];
}
//判断栈满
public boolean isfull(){
return top==maxsize-1;
}
//判断栈空
public boolean ifemty(){
return top==-1;
}
//入栈
public void push(int val){
//先判断栈是否满
if (isfull()){
System.out.println("栈满");
return;
}
top++;
Stack[top]=val;
}
//出栈
public int pop(){
//先判断是否为空
if (ifemty()){
throw new RuntimeException("栈为空没有数据");
}
int val=Stack[top];
top--;
return val;
}
//遍历栈
public void show(){
//先判断是否为空
if (ifemty()){
System.out.println("栈为空,没有数据");
return;
}
for (int i=top;i>=0;i--){
System.out.println(Stack[i]);
}
}
public int youxianji(char c){
if (c=='*'||c=='/'){
return 1;
}else if(c=='+'||c=='-'){
return 0;
}else{
return -1;
}
}
//返回栈顶元素
public int peek(){
return Stack[top];
}
//判断是否是符号
public boolean isoper(char c){
return c=='*'||c=='/'||c=='+'||c=='-';
}
//比较符号的优先级
public int yunxuan(int num1,int num2,char c){
int rec=0;
switch (c){
case '*':
rec=num1*num2;
break;
case '+':
rec=num1+num2;
break;
case '-':
rec=num2-num1;
break;
case '/':
rec=num2/num1;
break;
}
return rec;
}
}
public class Test6用栈实现表达式求值 {
public static void main(String[] args) {
ArrayStack1 numstack=new ArrayStack1(10);
ArrayStack1 operstack=new ArrayStack1(10);
int rec=0;//和
int num1=0;
int num2=0;
int opee=0;
char ch=' ';//用ch表示扫描的字符
int index=0;//代表索引
String keep="";
String biaodashi="5*8+6-40";
while (true){
ch=biaodashi.substring(index,index+1).charAt(0);
if (operstack.isoper(ch)){//判断是否是符号
//如果符号栈为空,就直接入符号栈
//否则,比较和符号栈中符号的优先级,如果当前大于符号就直接入符号栈
//如果当前小于等于栈中的,就从符号栈中pop(出栈)该符号出栈后不再栈中出一个符号进行运算,在把当前符号入栈。
if (!operstack.ifemty()) {
if (operstack.youxianji(ch) <= operstack.youxianji((char)operstack.peek())) {
num1 = numstack.pop();
num2 = numstack.pop();
opee = operstack.pop();//保存出栈符号。
rec = numstack.yunxuan(num1, num2, (char) opee);
numstack.push(rec);
operstack.push(ch);
} else {
operstack.push(ch);
}
} else {
operstack.push(ch);
}
}else {
keep+=ch;
if (index==biaodashi.length()-1){
numstack.push(Integer.parseInt(keep));
}else {
if (operstack.isoper(biaodashi.substring(index+1,index+2).charAt(0))){
numstack.push(Integer.parseInt(keep));
keep="";
}
}
}
index++;
if (index>=biaodashi.length()){
break;
}
}
while (true){
if (operstack.ifemty()){
break;
}
num1 = numstack.pop();
num2 = numstack.pop();
opee = (char) operstack.pop();
rec = numstack.yunxuan(num1, num2, (char) opee);
numstack.push(rec);
}
System.out.println(biaodashi+"="+numstack.pop());
}
}