您的位置:首页 > 其它

解析算术表达式

2017-05-14 11:55 274 查看

解析算术表达式的思路

算术表达式转换为后缀表达式



计算后缀表达式的值

如果是操作数,则压入栈中

如果是操作符,则从栈中取出两个值,进行运算,把运算之后的值,压入栈中,直到栈为空结束

Java代码

package StackAndQueue;

import java.util.Scanner;

/**
* Created by ln on 2017/5/14.
*/
public class Postfix3 {

public static void main(String[] args){
Scanner s = new Scanner(System.in);
String ss = s.nextLine();
String love = getValue(ss);
System.out.println(love);

int value = getR(love);
System.out.println(value);
}

//后缀表达式求值
public static int getR(String s){
Stack stack = new Stack(s.length());
char v;
int i1;
int i2;
int value;
for(int i=0;i<s.length();i++){
v = s.charAt(i);
if(v>='1'&&v<='9'){
stack.push(Integer.parseInt(v+""));
}else {
i1 = stack.pop();
i2 = stack.pop();
value = getYS(v,i2,i1);
stack.push(value);
}
}
return stack.pop();
}

//转换为后缀表达式
public static String getValue(String s){
Stack stack = new Stack(s.length());
String r = "";
char v;
int v_p;
char top;
int top_p;

for(int i=0;i<s.length();i++){
v = s.charAt(i);
if(v>='1'&&v<'9'){
r=r+v;
}else {
if(stack.isEmpty()){
stack.push(v);

4000
}else {
v_p = getL(v);
top = (char)stack.pop();
top_p=getL(top);
if(top_p==3||v=='('||(top_p==1&&v_p==2)){
stack.push(top);
stack.push(v);
}else if(v==')'){
while (top!='('){
r=r+top;
top=(char)stack.pop();
}
}else if(top_p==v_p){
r=r+top;
stack.push(v);
}else {
while (top!='('){
r=r+top;
if(stack.isEmpty()){
break;
}
top = (char)stack.pop();
}
stack.push(v);
}
}
}
}
while (!stack.isEmpty()){
top = (char)stack.pop();
r=r+top;
}
return r;
}

//
public static int getL(char c){
int v = -1;
switch (c){
case '+':
case '-':v=1;break;
case '*':
case '/':v=2;break;
case '(':
case ')':v=3;break;
}
return v;
}

//
public static int getYS(char c,int i1,int i2){
int v = 0;
switch (c){
case '+':v=i1+i2;break;
case '-':v=i1-i2;break;
case '*':v=i1*i2;break;
case '/':v=i1/i2;break;
}
return v;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: