日期:2014-05-20 浏览次数:20727 次
public class PostFix {
public static String postFix(String expression) {
CS401StackLinkedListImpl<Character> operandStack = new CS401StackLinkedListImpl<Character>();
String postfix = "";
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
Character temp;
switch (c) {
case ' ':
break;
case '+':
case '-':
while (operandStack.size() != 0) {
temp = operandStack.pop();
if (temp == '(') {
operandStack.push(temp);
break;
}
postfix += " " + temp;
}
operandStack.push(c);
postfix += " ";
break;
case '*':
case '/':
while (operandStack.size() != 0) {
temp = operandStack.pop();
if (temp == '('
------解决方案--------------------
temp == '+'
------解决方案--------------------
temp == '-') {
operandStack.push(temp);
break;
}
postfix += " " + temp;
}
operandStack.push(c);
postfix += " ";
break;
case '(':
operandStack.push(c);
break;
case ')':
while (operandStack.size() != 0) {
temp = operandStack.pop();
if (temp == '(') {
break;
}
postfix += " " + temp;
}
break;
default:
postfix += c;
break;
}
}
while (operandStack.size() != 0) {
postfix += " " + operandStack.pop();
}
return postfix;
}
public static int calculateArithmeticExp(String postfix) {
CS401StackLinkedListImpl<Integer> stack = new CS401StackLinkedListImpl<Integer>();
String[] strings = postfix.split(" ");
for (int i = 0; i < strings.length; i++) {
String temp = strings[i].trim();
if (temp == "")
continue;