四则运算的中缀转后缀



import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
*
* 应用:逆波兰表达式
*
* @author Leon.Chen
*
*/
public class CalculateString {

public BigDecimal calculateString(String str) {
char[] strs = str.toCharArray();
Stack<String> stack = new Stack<String>();

for (int i = 0; i < strs.length; i++) {
String stackStr = String.valueOf(strs[i]);
stack.push(stackStr);
if (")".equals(stack.top())) {
String subStr = null;
while (!"(".equals(stack.top())) {
stack.pop();
if (!"(".equals(stack.top())) {
subStr = addEnd(subStr, stack.top());
}
}
String pushStr = CalculateReversePolishExpression(subStr);
stack.pop();
stack.push(pushStr);
}

}
String resultStr = null;
while (stack.count != 0) {
resultStr = CalculateReversePolishExpression(stack.toString());
}
BigDecimal result = null;
if (resultStr != null) {
result = new BigDecimal(resultStr);
} else {
result = BigDecimal.ZERO;
}
return result.setScale(2, BigDecimal.ROUND_HALF_UP);
}

public String[] matcher(String regex, String str) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
String[] result = new String[list.size()];
return list.toArray(result);
}

public List<String> createReversePolishExpression(String subStr) {
String regex = "\\d+\\.{0,1}\\d*";
String[] numbers = matcher(regex, subStr);
String changeStr = subStr.replaceAll(regex, "0").replaceAll("\\-\\-0",
"-1").replaceAll("\\+\\-0", "+1").replaceAll("\\*\\-0", "*1")
.replaceAll("\\/\\-0", "/1");
char[] chars = changeStr.toCharArray();
int index = 0;
List<String> list = new ArrayList<String>();
for (int i = 0; i < chars.length; i++) {
String str = String.valueOf(chars[i]);
if ("0".equals(str)) {
list.add(numbers[index++]);
} else if ("1".equals(str)) {
list.add("-" + numbers[index++]);
} else {
list.add(str);
}
}
List<String> suffix = new ArrayList<String>();
Stack<String> operator = new Stack<String>();
for (int i = 0; i < list.size(); i++) {
if (!isOperatorType(list.get(i))) {
suffix.add(list.get(i));
} else {
if (operator.count == 0) {
operator.push(list.get(i));
} else {
while (operator.count != 0&&compare(operator.top(), list.get(i)) >= 0) {
String top = operator.top();
operator.pop();
suffix.add(top);
}
operator.push(list.get(i));

}
}
}

while (operator.count != 0) {
suffix.add(operator.top());
operator.pop();
}
return suffix;
}

public String CalculateReversePolishExpression(String subStr) {
List<String> suffix = createReversePolishExpression(subStr);
Stack<Double> stack = new Stack<Double>();
for (int i = 0; i < suffix.size(); i++) {
if (!isOperatorType(suffix.get(i))) {
stack.push(Double.valueOf(suffix.get(i)));
} else {
Double current = stack.top();
stack.pop();
Double previous = null;
if (stack.count != 0) {
previous = stack.top();
stack.pop();
} else {
previous = new Double(0);
}
Double result = calculate(suffix.get(i), previous, current);
stack.push(result);
}
}
return stack.top().toString();
}

public String addEnd(String str, String a) {
StringBuffer buf = new StringBuffer();
buf.append(a);
if (str != null) {
buf.append(str);
}
return buf.toString();
}

public boolean isOperatorType(String str) {
if (str.equals("+") || str.equals("-") || str.equals("*")
|| str.equals("/")) {
return true;
}
return false;
}

public int compare(String op1, String op2) {
Integer iop1 = getOperator(op1);
Integer iop2 = getOperator(op2);
return iop1.compareTo(iop2);
}

public Integer getOperator(String op) {
if ("+".equals(op) || "-".equals(op)) {
return new Integer(0);
}
if ("*".equals(op) || "/".equals(op)) {
return new Integer(1);
}
return null;
}

public Double calculate(String op, Double previous, Double current) {
if ("+".equals(op)) {
return previous + current;
}
if ("-".equals(op)) {
return previous - current;
}
if ("*".equals(op)) {
return previous * current;
}
if ("/".equals(op)) {
return previous / current;
}
return null;
}

public static void main(String[] args) {
String[] strs = new String[]{"(5+6)*7","(-1)/(-3)","1/(-3)","-1/7","7+(3*5)-(8+20/2)","4-(4-3*5+(2*4)+100)/10"};
for(int i=0;i<strs.length;i++){
BigDecimal result = new CalculateString().calculateString(strs[i]);
System.out.println(result.toString());
}

}

}

package graph;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
*
* 应用:逆波兰表达式
*
* @author Leon.Chen
*
*/
public class CalculateString {

public BigDecimal calculateString(String str) {
char[] strs = str.toCharArray();
Stack<String> stack = new Stack<String>();

for (int i = 0; i < strs.length; i++) {
String stackStr = String.valueOf(strs[i]);
stack.push(stackStr);
if (")".equals(stack.top())) {
String subStr = null;
while (!"(".equals(stack.top())) {
stack.pop();
if (!"(".equals(stack.top())) {
subStr = addEnd(subStr, stack.top());
}
}
String pushStr = CalculateReversePolishExpression(subStr);
stack.pop();
stack.push(pushStr);
}

}
String resultStr = null;
while (stack.count != 0) {
resultStr = CalculateReversePolishExpression(stack.toString());
}
BigDecimal result = null;
if (resultStr != null) {
result = new BigDecimal(resultStr);
} else {
result = BigDecimal.ZERO;
}
return result.setScale(2, BigDecimal.ROUND_HALF_UP);
}

public String[] matcher(String regex, String str) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
String[] result = new String[list.size()];
return list.toArray(result);
}

public List<String> createReversePolishExpression(String subStr) {
String regex = "\\d+\\.{0,1}\\d*";
String[] numbers = matcher(regex, subStr);
String changeStr = subStr.replaceAll(regex, "0").replaceAll("\\-\\-0",
"-1").replaceAll("\\+\\-0", "+1").replaceAll("\\*\\-0", "*1")
.replaceAll("\\/\\-0", "/1");
char[] chars = changeStr.toCharArray();
int index = 0;
List<String> list = new ArrayList<String>();
for (int i = 0; i < chars.length; i++) {
String str = String.valueOf(chars[i]);
if ("0".equals(str)) {
list.add(numbers[index++]);
} else if ("1".equals(str)) {
list.add("-" + numbers[index++]);
} else {
list.add(str);
}
}
List<String> suffix = new ArrayList<String>();
Stack<String> operator = new Stack<String>();
for (int i = 0; i < list.size(); i++) {
if (!isOperatorType(list.get(i))) {
suffix.add(list.get(i));
} else {
if (operator.count == 0) {
operator.push(list.get(i));
} else {
while (operator.count != 0&&compare(operator.top(), list.get(i)) >= 0) {
String top = operator.top();
operator.pop();
suffix.add(top);
}
operator.push(list.get(i));

}
}
}

while (operator.count != 0) {
suffix.add(operator.top());
operator.pop();
}
return suffix;
}

public String CalculateReversePolishExpression(String subStr) {
List<String> suffix = createReversePolishExpression(subStr);
Stack<Double> stack = new Stack<Double>();
for (int i = 0; i < suffix.size(); i++) {
if (!isOperatorType(suffix.get(i))) {
stack.push(Double.valueOf(suffix.get(i)));
} else {
Double current = stack.top();
stack.pop();
Double previous = null;
if (stack.count != 0) {
previous = stack.top();
stack.pop();
} else {
previous = new Double(0);
}
Double result = calculate(suffix.get(i), previous, current);
stack.push(result);
}
}
return stack.top().toString();
}

public String addEnd(String str, String a) {
StringBuffer buf = new StringBuffer();
buf.append(a);
if (str != null) {
buf.append(str);
}
return buf.toString();
}

public boolean isOperatorType(String str) {
if (str.equals("+") || str.equals("-") || str.equals("*")
|| str.equals("/")) {
return true;
}
return false;
}

public int compare(String op1, String op2) {
Integer iop1 = getOperator(op1);
Integer iop2 = getOperator(op2);
return iop1.compareTo(iop2);
}

public Integer getOperator(String op) {
if ("+".equals(op) || "-".equals(op)) {
return new Integer(0);
}
if ("*".equals(op) || "/".equals(op)) {
return new Integer(1);
}
return null;
}

public Double calculate(String op, Double previous, Double current) {
if ("+".equals(op)) {
return previous + current;
}
if ("-".equals(op)) {
return previous - current;
}
if ("*".equals(op)) {
return previous * current;
}
if ("/".equals(op)) {
return previous / current;
}
return null;
}

public static void main(String[] args) {
String[] strs = new String[]{"(5+6)*7","(-1)/(-3)","1/(-3)","-1/7","7+(3*5)-(8+20/2)","4-(4-3*5+(2*4)+100)/10"};
for(int i=0;i<strs.length;i++){
BigDecimal result = new CalculateString().calculateString(strs[i]);
System.out.println(result.toString());
}

}

}


自己写的stack


public class Stack<T> {
public StackNode<T> stackTop;
public int count;
public void push(T info) {
StackNode<T> node = new StackNode<T>();
node.info = info;
node.link = stackTop;
stackTop = node;
count++;
}

public void pop() {
if(stackTop == null) {
System.out.println("null stack");
} else {
stackTop = stackTop.link;
count--;
}

}

public boolean isEmpty() {
return count == 0;
}

public T top() {
if(stackTop == null) {
return null;
}
return stackTop.info;
}

public String toString(){
Stack<T> other = new Stack<T>();
while(count != 0){
T top = top();
pop();
other.push(top);
}
StringBuffer buf = new StringBuffer();
while(other.count !=0){
buf.append(other.top());
other.pop();
}
return buf.toString();
}

}


public class Stack<T> {
public StackNode<T> stackTop;
public int count;
public void push(T info) {
StackNode<T> node = new StackNode<T>();
node.info = info;
node.link = stackTop;
stackTop = node;
count++;
}

public void pop() {
if(stackTop == null) {
System.out.println("null stack");
} else {
stackTop = stackTop.link;
count--;
}

}

public boolean isEmpty() {
return count == 0;
}

public T top() {
if(stackTop == null) {
return null;
}
return stackTop.info;
}

public String toString(){
Stack<T> other = new Stack<T>();
while(count != 0){
T top = top();
pop();
other.push(top);
}
StringBuffer buf = new StringBuffer();
while(other.count !=0){
buf.append(other.top());
other.pop();
}
return buf.toString();
}

}


stack节点

public class StackNode<T> {
public StackNode<T> link;
public T info;
}





import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Eval {
public int eval(String exp){
List<String> list = infixExpToPostExp(exp);//转化成后缀表达式
return doEval(list);//真正求值
}

//遇到操作符压栈,遇到表达式从后缀表达式中弹出两个数,计算出结果,压入堆栈
private int doEval(List<String> list) {
Stack<String> stack = new Stack<String>();
String element;
int n1,n2,result;
try{
for(int i = 0; i < list.size();i++){
element = list.get(i);
if(isOperator(element)){
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
result = doOperate(n1,n2,element);
stack.push(new Integer(result).toString());
}else{
stack.push(element);
}
}
return Integer.parseInt(stack.pop());
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
}

private int doOperate(int n1, int n2, String operator) {
if(operator.equals("+"))
return n1 + n2;
else if(operator.equals("-"))
return n1 - n2;
else if(operator.equals("*"))
return n1 * n2;
else
return n1 / n2;
}

private boolean isOperator(String str){
return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/");
}

private List<String> infixExpToPostExp(String exp){//将中缀表达式转化成为后缀表达式
List<String> postExp = new ArrayList<String>();//存放转化的后缀表达式的链表
StringBuffer numBuffer = new StringBuffer();//用来保存一个数的
Stack<Character> opStack = new Stack<Character>();//操作符栈
char ch,preChar;
opStack.push('#');
try{
for(int i = 0; i < exp.length();){
ch = exp.charAt(i);
switch(ch){
case '+':
case '-':
case '*':
case '/':
preChar = opStack.peek();
// 如果栈里面的操作符优先级比当前的大,则把栈中优先级大的都添加到后缀表达式列表中
while(priority(preChar) >= priority(ch)){
postExp.add(""+preChar);
opStack.pop();
preChar = opStack.peek();
}
opStack.push(ch);
i++;
break;
case '(':
// 左括号直接压栈
opStack.push(ch);
i++;
break;
case ')':
// 右括号则直接把栈中左括号前面的弹出,并加入后缀表达式链表中
char c = opStack.pop();
while(c != '('){
postExp.add("" + c);
c = opStack.pop();
}
i++;
break;
// #号,代表表达式结束,可以直接把操作符栈中剩余的操作符全部弹出,并加入后缀表达式链表中
case '#':
char c1;
while(!opStack.isEmpty()){
c1 = opStack.pop();
if(c1 != '#')
postExp.add("" + c1);
}
i++;
break;
//过滤空白符
case ' ':
case '\t':
i++;
break;
// 数字则凑成一个整数,加入后缀表达式链表中
default:
if(Character.isDigit(ch)){
while(Character.isDigit(ch)){
numBuffer.append(ch);
ch = exp.charAt(++i);
}
postExp.add(numBuffer.toString());
numBuffer = new StringBuffer();
}else{
throw new IllegalExpressionException("illegal operator");
}
}
}
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
return postExp;
}

private int priority(char op){//定义优先级
switch(op){
case'+':
case'-':
return 1;
case'*':
case'/':
return 2;
case'(':
case'#':
return 0;
}
throw new IllegalExpressionException("Illegal operator");
}

public static void main(String[] args) {
Eval eval = new Eval();
int result = eval.eval("2+3+55*22+21*2+(3+2)*3+4*3+3*4#");
System.out.println(result);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值