WEB开发网
开发学院WEB开发Jsp JAVA数据结构示例---逆波兰式求值! 阅读

JAVA数据结构示例---逆波兰式求值!

 2008-01-05 09:04:28 来源:WEB开发网   
核心提示:package eXPRession;public class Calculate{ public static boolean isOperator(String operator){ if(operator.equals("+")operator.equals("-")op

  package eXPRession;
public class Calculate{
public static boolean isOperator(String operator){
if(operator.equals("+")operator.equals("-")operator.equals("*")operator.equals("/")operator.equals("(")operator.equals(")")) return true;
else return false;
}
public static int priority(String operator){
if(operator.equals("+")operator.equals("-")operator.equals("(")) return 1;
else if(operator.equals("*")operator.equals("/")) return 2;
else return 0;
}
public static String twoResult(String operator,String a,String b){
try{
String op=operator;
String rs=new String();
double x=Double.parseDouble(b);
double y=Double.parseDouble(a);
double z=0;
if(op.equals("+")) z=x+y;
else if(op.equals("-")) z=x-y;
else if(op.equals("*")) z=x*y;
else if(op.equals("/")) z=x/y;
else z=0;
return rs+z;
}
catch(NumberFormatException e){
System.out.println("input has something wrong!");
return "Error";
}
}
}





package expression;
import java.util.*;
public class Stacks{
private LinkedList list=new LinkedList();
int top=-1;
public void push(Object value){
top++;
list.addFirst(value);
}
public Object pop(){
Object temp=list.getFirst();
top--;
list.removeFirst();
return temp;

}
public Object top(){
return list.getFirst();
}
}



package expression;
import java.io.*;
import java.util.*;
public class Expression{
private ArrayList expression=new ArrayList();//存储中序表达式
private ArrayList right=new ArrayList();//存储右序表达式
private String result;//结果
//依据输入信息创建对象,将数值与操作符放入ArrayList中
private Expression(String input){
StringTokenizer st=new StringTokenizer(input,"+-*/()",true);
while(st.hasMoreElements()){
expression.add(st.nextToken());
}
}
//将中序表达式转换为右序表达式
private void toRight(){
Stacks aStack=new Stacks();
String operator;
int position=0;
while(true){
if(Calculate.isOperator((String)expression.get(position))){
if(aStack.top==-1((String)expression.get(position)).equals("(")){

Tags:JAVA 数据结构 波兰

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接