解析算术表达式
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; } }
相关文章推荐
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 数据结构之应用"栈(Stack)"实现: 解析算术表达式及计算
- 算术表达式解析(第二版) C++11版
- 解析带小括号的算术表达式--------用栈来实现的java算法
- 用MoonScript实现算术表达式解析
- 利用堆栈解析算术表达式一:基本过程
- 利用栈解析算术表达式
- 解析算术表达式
- 解析算术表达式
- 利用堆栈解析算术表达式
- 利用堆栈解析算术表达式一:基本过程
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 堆栈解析算术表达式
- 04 Java API:arraylist实现算术表达式的解析
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 数据结构之应用"栈(Stack)"实现: 解析算术表达式及计算
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 利用堆栈解析算术表达式
- dbms_aw.eval_number 解析算术表达式
- 堆栈解析算术表达式