package org.com.lin.test;
import java.util.Stack;
public class StackTest {
/**
* 加减乘除四则运算 此处只用于说明其实现思想,不做正式使用
*/
public static void test() {
Stack<Character> oStack = new Stack<Character>();
String s = "1+2+3+4/5/6-7/8*9+0";// 12+3+45/6/+78/9*0-+
// s = "2+3*4+5+6*7";//234*+5+6*7+
char[] charArr = s.toCharArray();
for (char c : charArr) {
if (Character.isDigit(c)) {
System.out.print(c);
} else {
if (oStack.size() == 0) {
oStack.push(c);
} else {
char topValue = oStack.peek();
if (topValue == '+' || topValue == '-') {
if (c == '*' || c == '/') {
oStack.push(c);
} else {
System.out.print(c);
// 循环判断栈顶元素符号是不是优先级较高,是,则出栈,否,则进栈
while (oStack.size() > 0) {
if (oStack.peek() == '*'
|| oStack.peek() == '/') {
System.out.print(oStack.pop());
} else {
break;
}
}
}
} else {
System.out.print(oStack.pop());
oStack.push(c);
}
}
}
}
while (oStack.size() > 0) {
System.out.print(oStack.pop());
}
}
public static void main(String[] args) {
test();
}
}