- 遇到操作数:直接输出(添加到后缀表达式中);
- 栈为空时,遇到运算符,直接入栈;
- 遇到左括号:将其入栈;
- 遇到右括号:执行出栈操作,并将出栈的元素输出,直到弹出栈的是左括号,左括号不输出;
- 遇到其他运算符:加减乘除:弹出所有优先级大于或者等于该运算符的栈顶元素,然后将该运算符入栈;
- 最终将栈中的元素依次出栈,输出;
计算9+(3-1)*2+8/2值
public static void main(String[] args) {
String s ="9+(3-1)*2+8/2";
ArrayList<Character> list = createStack(s);
Stack<Integer> stack = new Stack<Integer>();
//计算
list.forEach(character -> {
if (Character.isDigit(character)) {stack.push(getNumber(character));return ;}
Integer num1 = stack.pop();
Integer num2 = stack.pop();
switch (character){
case '*': stack.push(num2*num1);break;
case '+':;stack.push(num2+num1);break;
case '-':;stack.push(num2-num1);break;
case '/':;stack.push(num2/num1);break;
}
});
//结果
System.out.println();
System.out.println(stack.pop());
}
static int getNumber(Character c){
return Character.getNumericValue(c);
}
static ArrayList<Character> createStack(String s){
Stack<Character> stack = new Stack();
char[] chars = s.toCharArray();
ArrayList list = new ArrayList();
for(char c:chars){
// 遇到操作数:直接输出(添加到后缀表达式中);
if(Character.isLetterOrDigit(c)){
list.add(c);
}
//遇到左括号:将其入栈;
else if(c=='('){
stack.push(c);
}
//遇到右括号:执行出栈操作,并将出栈的元素输出,直到弹出栈的是左括号,左括号不输出;
else if(c==')'){
while (!(stack.peek()=='(')){
list.add(stack.pop());
}
stack.pop();
}
//遇到其他运算符:加减乘除:弹出所有优先级大于或者等于该运算符的栈顶元素,然后将该运算符入栈;
else{
while (!stack.isEmpty()&&(getPriority(c)<=getPriority((char)stack.peek()))){
list.add(stack.pop());
}
stack.push(c);
}
}
//最终将栈中的元素依次出栈,输出;
while (!stack.isEmpty()){
list.add(stack.pop());
}
list.forEach(charc->{
System.out.print(charc);
});
return list;
}
static int getPriority(char c){
if(c=='*' || c=='/'){
return 2;
}
else if(c=='+'||c=='-'){
return 1;
}
else {
return 0;
}
}
}```
网友评论