中缀表达式转换后缀表达式并求值(java实现)
中缀表达式转换后缀表达式
为了处理方便,编译程序通常把中缀表达式转化为后缀表达式,后缀表达式也称为“逆波兰式”指代双目运算符在两个运算对象的后面,例如:49*23+。
程序伪代码
1.实例化一个空栈S
2.扫描容器中的字符,执行以下操作
2.1若当前字符是运算对象即数字,则存入后缀表达式容器。
2.2若当前字符是运算符,且其优先级比栈顶运算符高,则使其入栈。
2.3若当前字符是运算符,且其优先级比栈顶运算符相等或低,则将栈顶元素弹出,并将当前字符压入栈中。
中缀表达式转换后缀表达式求值过程
待处理表达式 | 栈内状态(底<->顶) | 后缀表达式容器 |
---|
2*(9+6/3-5) | null | null |
*(9+6/3-5) | null | 2 |
(9+6/3-5) | * | 2 |
9+6/3-5) | *( | 2 |
+6/3-5) | *( | 29 |
6/3-5) | *(+ | 29 |
/3-5) | *(+ | 296 |
3-5) | *(+/ | 296 |
-5) | *(+/ | 2963 |
5) | *(- | 2963/+ |
) | *(- | 2963/+5 |
| * | 2963/+5- |
| | 2963/+5-* |
后缀表达式求值
在后缀表达式中,所有的计算按照运算符出现的顺序由左至右进行。
程序伪代码
1.实例化一个空栈S
2.扫描容器中的字符,执行以下操作
2.1若当前字符是运算对象即数字,则入栈。
弹出两个元素进行运算后入栈。
3.输出栈顶元素即结果
后缀表达式求值过程
读字符 | 栈内状态(底<->顶) | 说明 |
---|
2 | 2 | 2入栈 |
9 | 2 9 6 | 6入栈 |
3 | 2 9 6 3 | 3入栈 |
/ | 2 9 2 | 6,3出栈,执行/运算,将结果2入栈 |
+ | 2 11 | 9,2出栈,执行+运算,将结果11入栈 |
5 | 2 11 5 | 5入栈 |
- | 2 6 | 5,11出栈,执行-运算,将结果6入栈 |
* | 12 | 2,6出栈执行*操作,将结果12入栈 |
代码
package com.SimpleSort;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class WorkExpress {
static HashMap<Character, Integer> charTable = new HashMap<Character, Integer>();
public static void initChatTable(HashMap<Character, Integer> charTable) {
charTable.put('+', 1);
charTable.put('-', 1);
charTable.put('*', 2);
charTable.put('/', 2);
charTable.put('(', 0);
}
public static ArrayList<Character> listWork(char[] express ) {
List<Character> list = new ArrayList<Character>();
initChatTable(charTable);
Stack<Character> stack = new Stack<Character>();
for(char a : express){
if(a>='0'&& a<='9'){
list.add(a);
}else{
if(a == ')'){
while(stack.peek() != '('){
list.add(stack.pop());
}
stack.pop();
}else if(stack.size()==0 || compareChar(a, stack.peek()){ stack.push(a);
}else{
/**
* 当前运算符优先级小于等于栈顶运算符,
* 弹出栈顶运算符,并继续判断。
* **/
list.add(stack.pop());
while(!compareChar(a, stack.peek())){
list.add(stack.pop());
}
stack.push(a);
}
}
}
while(stack.size() != 0 ){
list.add(stack.pop());
}
return (ArrayList<Character>) list;
}
public static boolean compareChar(char currect,char stackTop){
if(currect == '('){
return true;
}
else if(charTable.get(currect)>charTable.get(stackTop)){
return true;
}
return false;
}
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
char[] express = sca.next().toCharArray();
ArrayList<Character> list = listWork(express);
Stack<Integer> work = new Stack<Integer>();
int result = 0;
System.out.println(list);
for(Character a : list){
System.out.println(result);
if(a>='0' && a <='9'){
work.push(a-48);
}else if(!work.isEmpty()){
Integer per = work.pop();
if(a == '+'){
result = (per + work.pop() );
work.push(result);
}
if(a == '-'){
result = ( work.pop() -per);
work.push(result);
}
if(a == '*'){
result = (per * work.pop());
work.push(result);
}
if(a == '/'){
result = (work.pop() / per) ;
work.push(result);
}
}
}
System.out.println(result);
}
}
欢迎学习,如有错误请及时联系本人修改。
希望指出本人不足共进步
LLY19960418