Java代码:
栈源码
public class InfixToSuffix {
public static void main(String[] args) {
infixToSuffix("(1+3)*(5-7)/9");
}
public static void infixToSuffix(String s) {
ListSimulateStack<Character> stack = new ListSimulateStack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <='9') {
System.out.print(s.charAt(i) + " ");
} else if (s.charAt(i) == '(') {
stack.push(s.charAt(i));
} else if (isOper(s.charAt(i))) {
while (true) {
if (stack.isEmpty()) {
stack.push(s.charAt(i));
break;
} else if (priority(s.charAt(i)) > priority(stack.peek())) {
stack.push(s.charAt(i));
break;
} else {
System.out.print(stack.pop() + " ");
}
}
} else if (s.charAt(i) == ')') {
do {
System.out.print(stack.pop() + " ");
} while (stack.peek() != '(');
stack.pop();
}
}
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
}
public static boolean isOper(char oper) {
return oper == '+' || oper == '-' || oper == '*' || oper == '/';
}
public static int priority(char oper) {
if (oper == '*' || oper == '/') {
return 1;
} else if (oper == '+' || oper == '-') {
return 0;
} else {
return -1;
}
}
}